code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import math def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase_ = input("Enter message: " ) UpperCAmelCase_ = int(input(f"""Enter key [2-{len(snake_case_ ) - 1}]: """ ) ) UpperCAmelCase_ = input("Encryption/Decryption [e/d]: " ) if mode.lower().startswith("e" ): UpperCAmelCase_ = encrypt_message(snake_case_ , snake_case_ ) elif mode.lower().startswith("d" ): UpperCAmelCase_ = decrypt_message(snake_case_ , snake_case_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"""Output:\n{text + "|"}""" ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : str ) -> str: '''simple docstring''' UpperCAmelCase_ = [""] * key for col in range(snake_case_ ): UpperCAmelCase_ = col while pointer < len(snake_case_ ): cipher_text[col] += message[pointer] pointer += key return "".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : str ) -> str: '''simple docstring''' UpperCAmelCase_ = math.ceil(len(snake_case_ ) / key ) UpperCAmelCase_ = key UpperCAmelCase_ = (num_cols * num_rows) - len(snake_case_ ) UpperCAmelCase_ = [""] * num_cols UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): UpperCAmelCase_ = 0 row += 1 return "".join(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
1
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" assert isinstance(A , A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Tuple: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase__ = JsonDatasetReader(A , cache_dir=A , keep_in_memory=A ).read() _check_json_dataset(A , A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase__ = features.copy() if features else default_expected_features lowercase__ = ( Features({feature: Value(A ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase__ = JsonDatasetReader(A , features=A , cache_dir=A ).read() _check_json_dataset(A , A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> List[str]: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} lowercase__ = features.copy() if features else default_expected_features lowercase__ = ( Features({feature: Value(A ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase__ = JsonDatasetReader(A , features=A , cache_dir=A ).read() assert isinstance(A , A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" lowercase__ = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} lowercase__ = features.copy() lowercase__ = ( Features({feature: Value(A ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase__ = tmp_path / '''cache''' lowercase__ = JsonDatasetReader(A , features=A , cache_dir=A ).read() assert isinstance(A , A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase__ = JsonDatasetReader(A , cache_dir=A , split=A ).read() _check_json_dataset(A , A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Tuple: """simple docstring""" if issubclass(A , A ): lowercase__ = jsonl_path elif issubclass(A , A ): lowercase__ = [jsonl_path] lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase__ = JsonDatasetReader(A , cache_dir=A ).read() _check_json_dataset(A , A ) def _SCREAMING_SNAKE_CASE (A , A , A=("train",) ) -> Tuple: """simple docstring""" assert isinstance(A , A ) for split in splits: lowercase__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> str: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase__ = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=A , keep_in_memory=A ).read() _check_json_datasetdict(A , A ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> List[Any]: """simple docstring""" lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase__ = features.copy() if features else default_expected_features lowercase__ = ( Features({feature: Value(A ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase__ = JsonDatasetReader({'''train''': jsonl_path} , features=A , cache_dir=A ).read() _check_json_datasetdict(A , A ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" if split: lowercase__ = {split: jsonl_path} else: lowercase__ = '''train''' lowercase__ = {'''train''': jsonl_path, '''test''': jsonl_path} lowercase__ = tmp_path / '''cache''' lowercase__ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase__ = JsonDatasetReader(A , cache_dir=A ).read() _check_json_datasetdict(A , A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _SCREAMING_SNAKE_CASE (A ) -> Dict: """simple docstring""" return json.load(A ) def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" return [json.loads(A ) for line in buffer] class __lowerCAmelCase : '''simple docstring''' @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase__ (self : int , UpperCamelCase : Tuple , UpperCamelCase : Optional[int] , UpperCamelCase : Dict ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase , UpperCamelCase , lines=UpperCamelCase ).write() buffer.seek(0 ) lowercase__ = load_json_function(UpperCamelCase ) assert isinstance(UpperCamelCase , UpperCamelCase ) assert isinstance(exported_content[0] , UpperCamelCase ) assert len(UpperCamelCase ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : int , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : List[str] ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase , UpperCamelCase , lines=UpperCamelCase , orient=UpperCamelCase ).write() buffer.seek(0 ) lowercase__ = load_json(UpperCamelCase ) assert isinstance(UpperCamelCase , UpperCamelCase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase ) == 10 @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Tuple , UpperCamelCase : Union[str, Any] ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase , UpperCamelCase , lines=UpperCamelCase , num_proc=2 ).write() buffer.seek(0 ) lowercase__ = load_json_function(UpperCamelCase ) assert isinstance(UpperCamelCase , UpperCamelCase ) assert isinstance(exported_content[0] , UpperCamelCase ) assert len(UpperCamelCase ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : int , UpperCamelCase : List[str] , UpperCamelCase : Tuple ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase , UpperCamelCase , lines=UpperCamelCase , orient=UpperCamelCase , num_proc=2 ).write() buffer.seek(0 ) lowercase__ = load_json(UpperCamelCase ) assert isinstance(UpperCamelCase , UpperCamelCase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase ) == 10 def UpperCamelCase__ (self : Dict , UpperCamelCase : Any ): '''simple docstring''' with pytest.raises(UpperCamelCase ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase , UpperCamelCase , num_proc=0 ) @pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def UpperCamelCase__ (self : str , UpperCamelCase : Dict , UpperCamelCase : Optional[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Any , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = tmp_path_factory.mktemp('''data''' ) / f"test.json.{extension}" lowercase__ = str(shared_datadir / f"test_file.json.{extension}" ) JsonDatasetWriter(UpperCamelCase , UpperCamelCase , compression=UpperCamelCase ).write() with fsspec.open(UpperCamelCase , '''rb''' , compression='''infer''' ) as f: lowercase__ = f.read() with fsspec.open(UpperCamelCase , '''rb''' , compression='''infer''' ) as f: lowercase__ = f.read() assert exported_content == original_content
2
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] lowercase : Optional[Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = [] A : Optional[int] = len(snake_case__ ) for i in range(snake_case__ ): A : float = -1 for j in range(i + 1 , snake_case__ ): if arr[i] < arr[j]: A : Dict = arr[j] break result.append(snake_case__ ) return result def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Any = [] for i, outer in enumerate(snake_case__ ): A : float = -1 for inner in arr[i + 1 :]: if outer < inner: A : List[str] = inner break result.append(snake_case__ ) return result def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = len(snake_case__ ) A : list[float] = [] A : list[float] = [-1] * arr_size for index in reversed(range(snake_case__ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: A : Dict = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) lowercase : Any = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
3
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : str = (KDPMaDiscreteScheduler,) lowerCamelCase : Optional[int] = 10 def __UpperCAmelCase ( self : List[Any] , **UpperCAmelCase__ : Optional[int] ) -> Any: lowerCAmelCase = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**UpperCAmelCase__ ) return config def __UpperCAmelCase ( self : List[str] ) -> Tuple: for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__ ) def __UpperCAmelCase ( self : Dict ) -> Optional[Any]: for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=UpperCAmelCase__ , beta_end=UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[Any] ) -> int: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=UpperCAmelCase__ ) def __UpperCAmelCase ( self : Union[str, Any] ) -> List[str]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__ ) def __UpperCAmelCase ( self : int ) -> Dict: lowerCAmelCase = self.scheduler_classes[0] lowerCAmelCase = self.get_scheduler_config(prediction_type='v_prediction' ) lowerCAmelCase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase = self.dummy_model() lowerCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = output.prev_sample lowerCAmelCase = torch.sum(torch.abs(UpperCAmelCase__ ) ) lowerCAmelCase = torch.mean(torch.abs(UpperCAmelCase__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.69_34E-07 ) < 1E-2 assert abs(result_mean.item() - 6.11_12E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __UpperCAmelCase ( self : Tuple ) -> Dict: if torch_device == "mps": return lowerCAmelCase = self.scheduler_classes[0] lowerCAmelCase = self.get_scheduler_config() lowerCAmelCase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase = self.dummy_model() lowerCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = output.prev_sample lowerCAmelCase = torch.sum(torch.abs(UpperCAmelCase__ ) ) lowerCAmelCase = torch.mean(torch.abs(UpperCAmelCase__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __UpperCAmelCase ( self : List[Any] ) -> Optional[Any]: if torch_device == "mps": return lowerCAmelCase = self.scheduler_classes[0] lowerCAmelCase = self.get_scheduler_config() lowerCAmelCase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps , device=UpperCAmelCase__ ) lowerCAmelCase = self.dummy_model() lowerCAmelCase = self.dummy_sample_deter.to(UpperCAmelCase__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase = scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = model(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = output.prev_sample lowerCAmelCase = torch.sum(torch.abs(UpperCAmelCase__ ) ) lowerCAmelCase = torch.mean(torch.abs(UpperCAmelCase__ ) ) if str(UpperCAmelCase__ ).startswith('cpu' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
4
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers UpperCAmelCase__ = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def UpperCAmelCase_ ( __snake_case , __snake_case=None ) -> Union[str, Any]: """simple docstring""" require_version(deps[pkg] , __snake_case )
5
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
def __lowerCAmelCase ( a__ , a__ , a__ ) -> list: __a = len(a__ ) __a = [[0] * n for i in range(a__ )] for i in range(a__ ): __a = y_points[i] for i in range(2 , a__ ): for j in range(a__ , a__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
6
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any],lowercase_ : str,lowercase_ : Optional[int]=3,lowercase_ : Optional[Any]=3_2,lowercase_ : str=3,lowercase_ : List[str]=1_0,lowercase_ : List[Any]=[1_0, 2_0, 3_0, 4_0],lowercase_ : Dict=[1, 1, 2, 1],lowercase_ : List[str]=True,lowercase_ : Tuple=True,lowercase_ : Optional[Any]="relu",lowercase_ : Tuple=3,lowercase_ : Any=None,)-> Tuple: '''simple docstring''' A__ = parent A__ = batch_size A__ = image_size A__ = num_channels A__ = embeddings_size A__ = hidden_sizes A__ = depths A__ = is_training A__ = use_labels A__ = hidden_act A__ = num_labels A__ = scope A__ = len(lowercase_ ) def snake_case__ ( self : Any )-> List[Any]: '''simple docstring''' A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ = self.get_config() return config, pixel_values def snake_case__ ( self : Any )-> Dict: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels,embeddings_size=self.embeddings_size,hidden_sizes=self.hidden_sizes,depths=self.depths,hidden_act=self.hidden_act,num_labels=self.num_labels,image_size=self.image_size,) def snake_case__ ( self : List[Any],lowercase_ : Optional[Any],lowercase_ : List[str] )-> List[str]: '''simple docstring''' A__ = FlaxRegNetModel(config=lowercase_ ) A__ = model(lowercase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape,(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2),) def snake_case__ ( self : Any,lowercase_ : int,lowercase_ : List[str] )-> Optional[Any]: '''simple docstring''' A__ = self.num_labels A__ = FlaxRegNetForImageClassification(config=lowercase_ ) A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels) ) def snake_case__ ( self : Tuple )-> str: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ = config_and_inputs A__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class A ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def snake_case__ ( self : Tuple )-> None: '''simple docstring''' A__ = FlaxRegNetModelTester(self ) A__ = ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> List[Any]: '''simple docstring''' 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 : List[str] )-> int: '''simple docstring''' return def snake_case__ ( self : str )-> Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def snake_case__ ( self : str )-> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @unittest.skip(reason='RegNet does not use inputs_embeds' ) def snake_case__ ( self : int )-> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason='RegNet does not support input and output embeddings' ) def snake_case__ ( self : Optional[Any] )-> str: '''simple docstring''' pass def snake_case__ ( self : int )-> Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(lowercase_ ) A__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = ['pixel_values'] self.assertListEqual(arg_names[:1],lowercase_ ) def snake_case__ ( self : Optional[Any] )-> Optional[Any]: '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str],lowercase_ : List[Any],lowercase_ : Optional[int] ): A__ = model_class(lowercase_ ) A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A__ = self.model_tester.num_stages self.assertEqual(len(lowercase_ ),expected_num_stages + 1 ) A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = True check_hidden_states_output(lowercase_,lowercase_,lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True check_hidden_states_output(lowercase_,lowercase_,lowercase_ ) def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): A__ = self._prepare_for_class(lowercase_,lowercase_ ) A__ = model_class(lowercase_ ) @jax.jit def model_jitted(lowercase_ : int,**lowercase_ : Dict ): return model(pixel_values=lowercase_,**lowercase_ ) with self.subTest('JIT Enabled' ): A__ = model_jitted(**lowercase_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): A__ = model_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ),len(lowercase_ ) ) for jitted_output, output in zip(lowercase_,lowercase_ ): self.assertEqual(jitted_output.shape,output.shape ) def _snake_case( ) -> Dict: '''simple docstring''' A__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_flax class A ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case__ ( self : Dict )-> Optional[int]: '''simple docstring''' return AutoImageProcessor.from_pretrained('facebook/regnet-y-040' ) if is_vision_available() else None @slow def snake_case__ ( self : Union[str, Any] )-> str: '''simple docstring''' A__ = FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040' ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=lowercase_,return_tensors='np' ) A__ = model(**lowercase_ ) # verify the logits A__ = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape,lowercase_ ) A__ = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3],lowercase_,atol=1E-4 ) )
7
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING lowerCAmelCase_ = logging.get_logger(__name__) @add_end_docstrings(__A ) class snake_case_ ( __A ): '''simple docstring''' def __init__( self : Any , *_UpperCamelCase : int , **_UpperCamelCase : Optional[Any] ) ->Union[str, Any]: super().__init__(*_UpperCamelCase , **_UpperCamelCase ) self.check_model_type(_UpperCamelCase ) def snake_case__( self : str , _UpperCamelCase : Dict=None , _UpperCamelCase : Dict=None , _UpperCamelCase : Optional[int]=None , **_UpperCamelCase : List[str] ) ->str: snake_case_, snake_case_ = {}, {} if padding is not None: snake_case_ = padding if truncation is not None: snake_case_ = truncation if top_k is not None: snake_case_ = top_k return preprocess_params, {}, postprocess_params def __call__( self : Optional[Any] , _UpperCamelCase : Union["Image.Image", str] , _UpperCamelCase : str = None , **_UpperCamelCase : Any ) ->Any: if isinstance(_UpperCamelCase , (Image.Image, str) ) and isinstance(_UpperCamelCase , _UpperCamelCase ): snake_case_ = {'''image''': image, '''question''': question} else: snake_case_ = image snake_case_ = super().__call__(_UpperCamelCase , **_UpperCamelCase ) return results def snake_case__( self : Union[str, Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple=False , _UpperCamelCase : List[Any]=False ) ->Optional[Any]: snake_case_ = load_image(inputs['''image'''] ) snake_case_ = self.tokenizer( inputs['''question'''] , return_tensors=self.framework , padding=_UpperCamelCase , truncation=_UpperCamelCase ) snake_case_ = self.image_processor(images=_UpperCamelCase , return_tensors=self.framework ) model_inputs.update(_UpperCamelCase ) return model_inputs def snake_case__( self : Union[str, Any] , _UpperCamelCase : List[Any] ) ->List[Any]: snake_case_ = self.model(**_UpperCamelCase ) return model_outputs def snake_case__( self : Tuple , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int]=5 ) ->Any: if top_k > self.model.config.num_labels: snake_case_ = self.model.config.num_labels if self.framework == "pt": snake_case_ = model_outputs.logits.sigmoid()[0] snake_case_, snake_case_ = probs.topk(_UpperCamelCase ) else: raise ValueError(f'''Unsupported framework: {self.framework}''' ) snake_case_ = scores.tolist() snake_case_ = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(_UpperCamelCase , _UpperCamelCase )]
8
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
from ..utils import DummyObject, requires_backends class _lowercase ( metaclass=A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = ['''keras_nlp'''] def __init__( self :Tuple , *lowerCAmelCase__ :Optional[Any] , **lowerCAmelCase__ :Dict ) -> Dict: requires_backends(self , ['''keras_nlp'''] )
9
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowercase_ = MODEL_FOR_MASKED_LM_MAPPING lowercase_ = TF_MODEL_FOR_MASKED_LM_MAPPING def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf") lowerCamelCase__: List[Any] =unmasker("My name is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ {"sequence": "My name is grouped", "score": 2.1E-0_5, "token": 38_015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1E-0_5, "token": 25_506, "token_str": " accuser"}, ] , ) lowerCamelCase__: List[str] =unmasker("The largest city in France is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ { "sequence": "The largest city in France is grouped", "score": 2.1E-0_5, "token": 38_015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1E-0_5, "token": 25_506, "token_str": " accuser", }, ] , ) lowerCamelCase__: List[str] =unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ {"sequence": "My name is Clara", "score": 2E-0_5, "token": 13_606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2E-0_5, "token": 3_499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9E-0_5, "token": 2_941, "token_str": " Te"}, ] , ) @require_torch def SCREAMING_SNAKE_CASE_ (self : str) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[str] =pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt") lowerCamelCase__: Tuple =unmasker("My name is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ {"sequence": "My name is Maul", "score": 2.2E-0_5, "token": 35_676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2E-0_5, "token": 16_416, "token_str": "ELS"}, ] , ) lowerCamelCase__: str =unmasker("The largest city in France is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ { "sequence": "The largest city in France is Maul", "score": 2.2E-0_5, "token": 35_676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2E-0_5, "token": 16_416, "token_str": "ELS"}, ] , ) lowerCamelCase__: str =unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ {"sequence": "My name is Patrick", "score": 2.1E-0_5, "token": 3_499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2E-0_5, "token": 2_941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2E-0_5, "token": 13_606, "token_str": " Clara"}, ] , ) lowerCamelCase__: Dict =unmasker("My name is <mask> <mask>" , top_k=2) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=6) , [ [ { "score": 2.2E-0_5, "token": 35_676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2E-0_5, "token": 16_416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2E-0_5, "token": 35_676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2E-0_5, "token": 16_416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] =pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt") # convert model to fp16 pipe.model.half() lowerCamelCase__: str =pipe("Paris is the [MASK] of France.") # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) @slow @require_torch def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: Any =pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt") self.run_large_test(UpperCAmelCase_) @slow @require_tf def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' lowerCamelCase__: List[Any] =pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf") self.run_large_test(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[int] =unmasker("My name is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1_573, "token_str": " Chris"}, ] , ) lowerCamelCase__: Tuple =unmasker("The largest city in France is <mask>") self.assertEqual( nested_simplify(UpperCAmelCase_) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2_201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12_790, "token_str": " Lyon", }, ] , ) lowerCamelCase__: int =unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3) self.assertEqual( nested_simplify(UpperCAmelCase_) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3_499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13_606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2_941, "token_str": " Te"}, ] , ) @require_torch def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt") lowerCamelCase__: Dict =None lowerCamelCase__: Dict =None self.run_pipeline_test(UpperCAmelCase_ , []) @require_tf def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: Tuple =pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf") lowerCamelCase__: Any =None lowerCamelCase__: Optional[int] =None self.run_pipeline_test(UpperCAmelCase_ , []) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int]) ->Optional[int]: '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)") lowerCamelCase__: List[Any] =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) lowerCamelCase__: Optional[int] =[ F"""This is another {tokenizer.mask_token} test""", ] return fill_masker, examples def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int) ->Optional[int]: '''simple docstring''' lowerCamelCase__: int =fill_masker.tokenizer lowerCamelCase__: str =fill_masker.model lowerCamelCase__: Optional[int] =fill_masker( F"""This is a {tokenizer.mask_token}""" , ) self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) lowerCamelCase__: List[Any] =fill_masker([F"""This is a {tokenizer.mask_token}"""]) self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) lowerCamelCase__: Optional[Any] =fill_masker([F"""This is a {tokenizer.mask_token}""", F"""Another {tokenizer.mask_token} great test."""]) self.assertEqual( UpperCAmelCase_ , [ [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ], [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ], ] , ) with self.assertRaises(UpperCAmelCase_): fill_masker([None]) # No mask_token is not supported with self.assertRaises(UpperCAmelCase_): fill_masker("This is") self.run_test_top_k(UpperCAmelCase_ , UpperCAmelCase_) self.run_test_targets(UpperCAmelCase_ , UpperCAmelCase_) self.run_test_top_k_targets(UpperCAmelCase_ , UpperCAmelCase_) self.fill_mask_with_duplicate_targets_and_top_k(UpperCAmelCase_ , UpperCAmelCase_) self.fill_mask_with_multiple_masks(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] =tokenizer.get_vocab() lowerCamelCase__: Optional[int] =sorted(vocab.keys())[:2] # Pipeline argument lowerCamelCase__: Tuple =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , targets=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =fill_masker(F"""This is a {tokenizer.mask_token}""") self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) lowerCamelCase__: Tuple ={vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , UpperCAmelCase_) lowerCamelCase__: List[str] =[tokenizer.decode([x]) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(UpperCAmelCase_)) # Call argument lowerCamelCase__: List[Any] =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=UpperCAmelCase_) self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) lowerCamelCase__: Optional[int] ={vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , UpperCAmelCase_) lowerCamelCase__: str =[tokenizer.decode([x]) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(UpperCAmelCase_)) # Score equivalence lowerCamelCase__: List[str] =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=UpperCAmelCase_) lowerCamelCase__: str =[top_mask["token_str"] for top_mask in outputs] lowerCamelCase__: Dict =[top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCAmelCase_) == set(UpperCAmelCase_): lowerCamelCase__: Union[str, Any] =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=UpperCAmelCase_) lowerCamelCase__: Any =[top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(UpperCAmelCase_) , nested_simplify(UpperCAmelCase_)) # Raises with invalid with self.assertRaises(UpperCAmelCase_): lowerCamelCase__: Optional[int] =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=[]) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(UpperCAmelCase_): lowerCamelCase__: Dict =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=[""]) with self.assertRaises(UpperCAmelCase_): lowerCamelCase__: Dict =fill_masker(F"""This is a {tokenizer.mask_token}""" , targets="") def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Optional[int] =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , top_k=2) lowerCamelCase__: List[str] =fill_masker(F"""This is a {tokenizer.mask_token}""") self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) lowerCamelCase__: Dict =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) lowerCamelCase__: Tuple =fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=2) self.assertEqual( UpperCAmelCase_ , [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ] , ) self.assertEqual(nested_simplify(UpperCAmelCase_) , nested_simplify(UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Tuple =tokenizer.get_vocab() lowerCamelCase__: Any =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) # top_k=2, ntargets=3 lowerCamelCase__: List[str] =sorted(vocab.keys())[:3] lowerCamelCase__: List[Any] =fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=2 , targets=UpperCAmelCase_) # If we use the most probably targets, and filter differently, we should still # have the same results lowerCamelCase__: Union[str, Any] =[el["token_str"] for el in sorted(UpperCAmelCase_ , key=lambda UpperCAmelCase_: x["score"] , reverse=UpperCAmelCase_)] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCAmelCase_).issubset(UpperCAmelCase_): lowerCamelCase__: int =fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=3 , targets=UpperCAmelCase_) # They should yield exactly the same result self.assertEqual(nested_simplify(UpperCAmelCase_) , nested_simplify(UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]) ->List[str]: '''simple docstring''' lowerCamelCase__: Any =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.get_vocab() # String duplicates + id duplicates lowerCamelCase__: Optional[Any] =sorted(vocab.keys())[:3] lowerCamelCase__: Optional[Any] =[targets[0], targets[1], targets[0], targets[2], targets[1]] lowerCamelCase__: Union[str, Any] =fill_masker(F"""My name is {tokenizer.mask_token}""" , targets=UpperCAmelCase_ , top_k=10) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(UpperCAmelCase_) , 3) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =FillMaskPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_) lowerCamelCase__: Tuple =fill_masker( F"""This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}""" , top_k=2) self.assertEqual( UpperCAmelCase_ , [ [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ], [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ], [ {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, {"sequence": ANY(UpperCAmelCase_), "score": ANY(UpperCAmelCase_), "token": ANY(UpperCAmelCase_), "token_str": ANY(UpperCAmelCase_)}, ], ] , )
10
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
import math import unittest def _UpperCAmelCase (UpperCamelCase__ : int ): assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(UpperCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class lowerCAmelCase__ ( unittest.TestCase): '''simple docstring''' def _lowerCamelCase ( self) -> Optional[Any]: self.assertTrue(is_prime(2)) self.assertTrue(is_prime(3)) self.assertTrue(is_prime(5)) self.assertTrue(is_prime(7)) self.assertTrue(is_prime(1_1)) self.assertTrue(is_prime(1_3)) self.assertTrue(is_prime(1_7)) self.assertTrue(is_prime(1_9)) self.assertTrue(is_prime(2_3)) self.assertTrue(is_prime(2_9)) def _lowerCamelCase ( self) -> List[Any]: with self.assertRaises(__lowerCamelCase): is_prime(-1_9) self.assertFalse( is_prime(0) , "Zero doesn't have any positive factors, primes must have exactly two." , ) self.assertFalse( is_prime(1) , "One only has 1 positive factor, primes must have exactly two." , ) self.assertFalse(is_prime(2 * 2)) self.assertFalse(is_prime(2 * 3)) self.assertFalse(is_prime(3 * 3)) self.assertFalse(is_prime(3 * 5)) self.assertFalse(is_prime(3 * 5 * 7)) if __name__ == "__main__": unittest.main()
11
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed UpperCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase__ ( A__ : Union[str, Any]=2 , A__ : List[Any]=3 , A__ : Optional[int]=16 , A__ : int = 10 , A__ : int = 2 ): '''simple docstring''' def get_dataset(A__ : Union[str, Any] ): __lowerCamelCase = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(A__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) __lowerCamelCase = get_dataset(A__ ) __lowerCamelCase = get_dataset(A__ ) __lowerCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) __lowerCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def lowerCamelCase__ ( A__ : List[str] , A__ : List[str] , A__ : Optional[Any] , A__ : Tuple , A__ : Dict , A__ : Union[str, Any]=None ): '''simple docstring''' __lowerCamelCase = [] for epoch in range(A__ ): # Train quickly model.train() for batch in dataloader: __lowerCamelCase, __lowerCamelCase = batch __lowerCamelCase = model(A__ ) __lowerCamelCase = torch.nn.functional.mse_loss(A__ , A__ ) accelerator.backward(A__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class lowerCamelCase__( nn.Module): def __init__( self: Dict ): super().__init__() __lowerCamelCase = nn.Parameter(torch.randn(1 ) ) __lowerCamelCase = nn.Parameter(torch.randn(1 ) ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Union[str, Any] ): return x * self.a + self.b class lowerCamelCase__( unittest.TestCase): def lowerCAmelCase__ ( self: int ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(total_limit=1 , project_dir=UpperCamelCase_ , automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def lowerCAmelCase__ ( self: Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() # Train baseline __lowerCamelCase = Accelerator() __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial __lowerCamelCase = os.path.join(UpperCamelCase_ , """initial""" ) accelerator.save_state(UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() __lowerCamelCase = train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() # Train partially set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = Accelerator() __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) accelerator.load_state(UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = train(2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save everything __lowerCamelCase = os.path.join(UpperCamelCase_ , """checkpoint""" ) accelerator.save_state(UpperCamelCase_ ) # Load everything back in and make sure all states work accelerator.load_state(UpperCamelCase_ ) test_rands += train(1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[str] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() __lowerCamelCase = train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() # Train partially set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=UpperCamelCase_ ) __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = train(2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = torch.tensor([1, 2, 3] ) __lowerCamelCase = torch.tensor([2, 3, 4] ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(net.parameters() ) __lowerCamelCase = Accelerator() with self.assertRaises(UpperCamelCase_ ) as ve: accelerator.register_for_checkpointing(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def lowerCAmelCase__ ( self: Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase = torch.optim.lr_scheduler.StepLR(UpperCamelCase_ , step_size=1 , gamma=0.99 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() __lowerCamelCase = scheduler.state_dict() train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) self.assertNotEqual(UpperCamelCase_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(UpperCamelCase_ , scheduler.state_dict() ) def lowerCAmelCase__ ( self: Dict ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ , total_limit=2 ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase = accelerator.prepare(UpperCamelCase_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = ["""torchrun""", F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(UpperCamelCase_ , env=os.environ.copy() ) if __name__ == "__main__": UpperCAmelCase_ = '/tmp/accelerate/state_checkpointing' UpperCAmelCase_ = DummyModel() UpperCAmelCase_ = torch.optim.Adam(params=model.parameters(), lr=1E-3) UpperCAmelCase_ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) UpperCAmelCase_ , UpperCAmelCase_ = dummy_dataloaders() UpperCAmelCase_ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline UpperCAmelCase_ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert param_device.type == accelerator.device.type UpperCAmelCase_ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
12
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __lowercase : """simple docstring""" def __init__( self : Optional[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any]=3 , lowerCAmelCase__ : List[Any]=32 , lowerCAmelCase__ : Any=3 , lowerCAmelCase__ : Optional[Any]=10 , lowerCAmelCase__ : Any=[8, 16, 32, 64] , lowerCAmelCase__ : Tuple=[1, 1, 2, 1] , lowerCAmelCase__ : List[str]=True , lowerCAmelCase__ : Dict=True , lowerCAmelCase__ : Optional[int]="relu" , lowerCAmelCase__ : str=3 , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : List[Any]=["stage2", "stage3", "stage4"] , lowerCAmelCase__ : List[str]=[2, 3, 4] , lowerCAmelCase__ : int=1 , ): SCREAMING_SNAKE_CASE_: Tuple = parent SCREAMING_SNAKE_CASE_: str = batch_size SCREAMING_SNAKE_CASE_: List[Any] = image_size SCREAMING_SNAKE_CASE_: Optional[int] = num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = embeddings_size SCREAMING_SNAKE_CASE_: Tuple = hidden_sizes SCREAMING_SNAKE_CASE_: str = depths SCREAMING_SNAKE_CASE_: Dict = is_training SCREAMING_SNAKE_CASE_: Tuple = use_labels SCREAMING_SNAKE_CASE_: List[str] = hidden_act SCREAMING_SNAKE_CASE_: Optional[int] = num_labels SCREAMING_SNAKE_CASE_: Optional[int] = scope SCREAMING_SNAKE_CASE_: Union[str, Any] = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = out_features SCREAMING_SNAKE_CASE_: Any = out_indices SCREAMING_SNAKE_CASE_: str = num_groups def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_: int = None if self.use_labels: SCREAMING_SNAKE_CASE_: List[Any] = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_: str = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int]): SCREAMING_SNAKE_CASE_: List[Any] = BitModel(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() SCREAMING_SNAKE_CASE_: Optional[Any] = model(lowerCAmelCase__) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int): SCREAMING_SNAKE_CASE_: Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_: Tuple = BitForImageClassification(lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() SCREAMING_SNAKE_CASE_: Union[str, Any] = model(lowerCAmelCase__ , labels=lowerCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Dict = BitBackbone(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() SCREAMING_SNAKE_CASE_: Optional[Any] = model(lowerCAmelCase__) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE_: Optional[Any] = None SCREAMING_SNAKE_CASE_: Optional[int] = BitBackbone(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() SCREAMING_SNAKE_CASE_: List[str] = model(lowerCAmelCase__) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE_: str = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" _UpperCAmelCase : Dict = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () _UpperCAmelCase : Optional[Any] = ( {'''feature-extraction''': BitModel, '''image-classification''': BitForImageClassification} if is_torch_available() else {} ) _UpperCAmelCase : List[Any] = False _UpperCAmelCase : List[str] = False _UpperCAmelCase : int = False _UpperCAmelCase : Union[str, Any] = False _UpperCAmelCase : str = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Optional[int] = BitModelTester(self) SCREAMING_SNAKE_CASE_: Dict = ConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : int): 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 _SCREAMING_SNAKE_CASE ( self : Dict): return @unittest.skip(reason="Bit does not output attentions") def _SCREAMING_SNAKE_CASE ( self : Dict): pass @unittest.skip(reason="Bit does not use inputs_embeds") def _SCREAMING_SNAKE_CASE ( self : Any): pass @unittest.skip(reason="Bit does not support input and output embeddings") def _SCREAMING_SNAKE_CASE ( self : Tuple): pass def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: List[Any] = model_class(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_: Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_: Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_: int = model_class(config=lowerCAmelCase__) for name, module in model.named_modules(): if isinstance(lowerCAmelCase__ , (nn.BatchNormad, nn.GroupNorm)): self.assertTrue( torch.all(module.weight == 1) , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) self.assertTrue( torch.all(module.bias == 0) , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): def check_hidden_states_output(lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str]): SCREAMING_SNAKE_CASE_: Union[str, Any] = model_class(lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_: str = model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__)) SCREAMING_SNAKE_CASE_: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_: List[str] = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase__) , expected_num_stages + 1) # Bit'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] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_: Union[str, Any] = ["preactivation", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE_: Optional[Any] = layer_type SCREAMING_SNAKE_CASE_: Optional[Any] = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_: Tuple = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) @unittest.skip(reason="Bit does not use feedforward chunking") def _SCREAMING_SNAKE_CASE ( self : str): pass def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__) @slow def _SCREAMING_SNAKE_CASE ( self : Any): for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_: List[Any] = BitModel.from_pretrained(lowerCAmelCase__) self.assertIsNotNone(lowerCAmelCase__) def A_ ( ): SCREAMING_SNAKE_CASE_: List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowercase ( unittest.TestCase ): """simple docstring""" @cached_property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = self.default_image_processor SCREAMING_SNAKE_CASE_: Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_: List[Any] = image_processor(images=lowerCAmelCase__ , return_tensors="pt").to(lowerCAmelCase__) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_: int = model(**lowerCAmelCase__) # verify the logits SCREAMING_SNAKE_CASE_: int = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = torch.tensor([[-0.6526, -0.5263, -1.4398]]).to(lowerCAmelCase__) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4)) @require_torch class __lowercase ( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" _UpperCAmelCase : int = (BitBackbone,) if is_torch_available() else () _UpperCAmelCase : List[str] = BitConfig _UpperCAmelCase : str = False def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_: Union[str, Any] = BitModelTester(self)
13
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> list: """simple docstring""" A__ = 0 # Number of processes finished A__ = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. A__ = [0] * no_of_process # List to include calculation results A__ = [0] * no_of_process # Sort by arrival time. A__ = [burst_time[i] for i in np.argsort(lowercase_ )] A__ = [process_name[i] for i in np.argsort(lowercase_ )] arrival_time.sort() while no_of_process > finished_process_count: A__ = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: A__ = arrival_time[i] A__ = 0 # Index showing the location of the process being performed A__ = 0 # Saves the current response ratio. A__ = 0 for i in range(0 , lowercase_ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: A__ = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: A__ = temp A__ = i # Calculate the turn around time A__ = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. A__ = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> list: """simple docstring""" A__ = [0] * no_of_process for i in range(0 , lowercase_ ): A__ = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _lowerCamelCase : List[Any] = 5 _lowerCamelCase : Any = ["""A""", """B""", """C""", """D""", """E"""] _lowerCamelCase : Optional[int] = [1, 2, 3, 4, 5] _lowerCamelCase : Optional[int] = [1, 2, 3, 4, 5] _lowerCamelCase : Union[str, Any] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _lowerCamelCase : Tuple = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("""Process name \tArrival time \tBurst time \tTurn around time \tWaiting time""") for i in range(0, no_of_process): print( F'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' F'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(F'''average waiting time : {mean(waiting_time):.5f}''') print(F'''average turn around time : {mean(turn_around_time):.5f}''')
14
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
from __future__ import annotations import math from collections.abc import Callable def UpperCAmelCase ( a_ , a_ , a_ , a_ = 1_0_0 , ) -> float: """simple docstring""" __A = x_start __A = fnc(a_ ) __A = 0.0 for _ in range(a_ ): # Approximates curve as a sequence of linear lines and sums their length __A = (x_end - x_start) / steps + xa __A = fnc(a_ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step __A = xa __A = fxa return length if __name__ == "__main__": def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" return math.sin(1_0 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') SCREAMING_SNAKE_CASE :Tuple = 10 while i <= 10_0000: print(f'''With {i} steps: {line_length(f, -10, 10, i)}''') i *= 10
15
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
"""simple docstring""" # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class __A ( A_ ,A_ ,A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} lowerCAmelCase : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"} ) lowerCAmelCase : int = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase ( self : int ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) lowercase__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,cross_attention_dim=32 ,) torch.manual_seed(0 ) lowercase__ : Any = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) torch.manual_seed(0 ) lowercase__ : List[str] = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='''scaled_linear''' ,clip_sample=_snake_case ,set_alpha_to_one=_snake_case ,) torch.manual_seed(0 ) lowercase__ : List[str] = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,) torch.manual_seed(0 ) lowercase__ : Optional[Any] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) lowercase__ : List[Any] = CLIPTextModel(_snake_case ) lowercase__ : Union[str, Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) lowercase__ : Dict = { '''unet''': unet, '''controlnet''': controlnet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCAmelCase ( self : Any ,_snake_case : List[Any] ,_snake_case : Any=0 ) -> Any: """simple docstring""" if str(_snake_case ).startswith('''mps''' ): lowercase__ : Optional[Any] = torch.manual_seed(_snake_case ) else: lowercase__ : str = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) lowercase__ : List[Any] = 2 lowercase__ : Optional[int] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_snake_case ,device=torch.device(_snake_case ) ,) lowercase__ : str = floats_tensor(control_image.shape ,rng=random.Random(_snake_case ) ).to(_snake_case ) lowercase__ : Optional[Any] = image.cpu().permute(0 ,2 ,3 ,1 )[0] lowercase__ : Optional[Any] = Image.fromarray(np.uinta(_snake_case ) ).convert('''RGB''' ).resize((64, 64) ) lowercase__ : Union[str, Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''image''': image, '''control_image''': control_image, } return inputs def UpperCAmelCase ( self : Optional[int] ) -> Dict: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def UpperCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def UpperCAmelCase ( self : Any ) -> str: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class __A ( A_ ,A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Dict = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} lowerCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def UpperCAmelCase ( self : Tuple ) -> Any: """simple docstring""" torch.manual_seed(0 ) lowercase__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,cross_attention_dim=32 ,) torch.manual_seed(0 ) def init_weights(_snake_case : Optional[int] ): if isinstance(_snake_case ,torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) lowercase__ : Any = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(_snake_case ) torch.manual_seed(0 ) lowercase__ : Any = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(_snake_case ) torch.manual_seed(0 ) lowercase__ : Dict = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='''scaled_linear''' ,clip_sample=_snake_case ,set_alpha_to_one=_snake_case ,) torch.manual_seed(0 ) lowercase__ : List[str] = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,) torch.manual_seed(0 ) lowercase__ : List[Any] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) lowercase__ : int = CLIPTextModel(_snake_case ) lowercase__ : Union[str, Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) lowercase__ : int = MultiControlNetModel([controlneta, controlneta] ) lowercase__ : Optional[Any] = { '''unet''': unet, '''controlnet''': controlnet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCAmelCase ( self : Optional[Any] ,_snake_case : Dict ,_snake_case : Union[str, Any]=0 ) -> List[Any]: """simple docstring""" if str(_snake_case ).startswith('''mps''' ): lowercase__ : int = torch.manual_seed(_snake_case ) else: lowercase__ : Dict = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) lowercase__ : int = 2 lowercase__ : Optional[Any] = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_snake_case ,device=torch.device(_snake_case ) ,), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=_snake_case ,device=torch.device(_snake_case ) ,), ] lowercase__ : Dict = floats_tensor(control_image[0].shape ,rng=random.Random(_snake_case ) ).to(_snake_case ) lowercase__ : Dict = image.cpu().permute(0 ,2 ,3 ,1 )[0] lowercase__ : Optional[int] = Image.fromarray(np.uinta(_snake_case ) ).convert('''RGB''' ).resize((64, 64) ) lowercase__ : Any = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''image''': image, '''control_image''': control_image, } return inputs def UpperCAmelCase ( self : Dict ) -> List[str]: """simple docstring""" lowercase__ : Dict = self.get_dummy_components() lowercase__ : Dict = self.pipeline_class(**_snake_case ) pipe.to(_snake_case ) lowercase__ : Optional[Any] = 10.0 lowercase__ : Tuple = 4 lowercase__ : Dict = self.get_dummy_inputs(_snake_case ) lowercase__ : Optional[Any] = steps lowercase__ : Any = scale lowercase__ : Optional[Any] = pipe(**_snake_case )[0] lowercase__ : List[str] = self.get_dummy_inputs(_snake_case ) lowercase__ : Optional[int] = steps lowercase__ : int = scale lowercase__ : List[str] = pipe(**_snake_case ,control_guidance_start=0.1 ,control_guidance_end=0.2 )[0] lowercase__ : int = self.get_dummy_inputs(_snake_case ) lowercase__ : Optional[int] = steps lowercase__ : Dict = scale lowercase__ : Dict = pipe(**_snake_case ,control_guidance_start=[0.1, 0.3] ,control_guidance_end=[0.2, 0.7] )[0] lowercase__ : Dict = self.get_dummy_inputs(_snake_case ) lowercase__ : List[Any] = steps lowercase__ : Optional[int] = scale lowercase__ : List[Any] = pipe(**_snake_case ,control_guidance_start=0.4 ,control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def UpperCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def UpperCAmelCase ( self : List[str] ) -> Dict: """simple docstring""" lowercase__ : Union[str, Any] = self.get_dummy_components() lowercase__ : Optional[Any] = self.pipeline_class(**_snake_case ) pipe.to(_snake_case ) pipe.set_progress_bar_config(disable=_snake_case ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(_snake_case ) except NotImplementedError: pass @slow @require_torch_gpu class __A ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase ( self : Any ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ : int = ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny''' ) lowercase__ : Any = StableDiffusionControlNetImgaImgPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' ,safety_checker=_snake_case ,controlnet=_snake_case ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=_snake_case ) lowercase__ : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) lowercase__ : List[str] = '''evil space-punk bird''' lowercase__ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''' ).resize((512, 512) ) lowercase__ : Tuple = load_image( '''https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png''' ).resize((512, 512) ) lowercase__ : List[Any] = pipe( _snake_case ,_snake_case ,control_image=_snake_case ,generator=_snake_case ,output_type='''np''' ,num_inference_steps=50 ,strength=0.6 ,) lowercase__ : List[Any] = output.images[0] assert image.shape == (512, 512, 3) lowercase__ : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy''' ) assert np.abs(expected_image - image ).max() < 9e-2
16
'''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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
"""simple docstring""" def _A ( UpperCamelCase_ : float, UpperCamelCase_ : float) -> float: '''simple docstring''' if density <= 0: raise ValueError("Impossible fluid density") if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus") return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
17
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Union[str, Any] = { '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class a__ ( A__ ): A = 'gpt_neo' A = ['past_key_values'] A = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self : Tuple,_A : str=5_0257,_A : Dict=2048,_A : Any=2048,_A : Optional[int]=24,_A : List[str]=[[["global", "local"], 12]],_A : List[str]=16,_A : Union[str, Any]=None,_A : Optional[Any]=256,_A : Any="gelu_new",_A : int=0.0,_A : Optional[Any]=0.0,_A : Any=0.0,_A : str=0.1,_A : Any=1E-5,_A : int=0.02,_A : List[Any]=True,_A : Union[str, Any]=5_0256,_A : List[str]=5_0256,**_A : Tuple,): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = hidden_size SCREAMING_SNAKE_CASE_ : str = num_layers SCREAMING_SNAKE_CASE_ : str = num_heads SCREAMING_SNAKE_CASE_ : Dict = intermediate_size SCREAMING_SNAKE_CASE_ : str = window_size SCREAMING_SNAKE_CASE_ : Tuple = activation_function SCREAMING_SNAKE_CASE_ : Union[str, Any] = resid_dropout SCREAMING_SNAKE_CASE_ : int = embed_dropout SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE_ : Tuple = classifier_dropout SCREAMING_SNAKE_CASE_ : Tuple = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = use_cache SCREAMING_SNAKE_CASE_ : Tuple = bos_token_id SCREAMING_SNAKE_CASE_ : Tuple = eos_token_id SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_types SCREAMING_SNAKE_CASE_ : str = self.expand_attention_types_params(_A ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " F'but is `len(config.attention_layers) = {len(self.attention_layers )}`, ' F'`config.num_layers = {self.num_layers}`. ' "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=_A,eos_token_id=_A,**_A ) @staticmethod def __UpperCamelCase ( _A : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _snake_case ( lowerCAmelCase : Tuple , lowerCAmelCase : Any , lowerCAmelCase : Tuple , lowerCAmelCase : List[str] ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ : str = input.size() SCREAMING_SNAKE_CASE_ : Any = len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = shape[dimension] SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.arange(0 , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.div(sizedim - size , lowerCAmelCase , rounding_mode="floor" ) + 1 SCREAMING_SNAKE_CASE_ : Tuple = torch.arange(lowerCAmelCase ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE_ : List[str] = [slice(lowerCAmelCase )] * rank SCREAMING_SNAKE_CASE_ : List[Any] = indices SCREAMING_SNAKE_CASE_ : Optional[Any] = input[s] SCREAMING_SNAKE_CASE_ : Any = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(lowerCAmelCase ) def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : Dict ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ : str = torch.arange(1 , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : List[str] = torch.remainder(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Optional[int] = remainders == 0 SCREAMING_SNAKE_CASE_ : str = candidates[divisor_indices] SCREAMING_SNAKE_CASE_ : str = torch.max(lowerCAmelCase ) return largest_divisor, torch.div(lowerCAmelCase , lowerCAmelCase , rounding_mode="floor" ) class a__ ( A__ ): @property def __UpperCamelCase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(_A,direction="inputs" ) SCREAMING_SNAKE_CASE_ : int = {0: "batch", 1: "past_sequence + sequence"} else: SCREAMING_SNAKE_CASE_ : Dict = {0: "batch", 1: "sequence"} return common_inputs @property def __UpperCamelCase ( self : List[Any] ): """simple docstring""" return self._config.num_heads def __UpperCamelCase ( self : Optional[int],_A : PreTrainedTokenizer,_A : int = -1,_A : int = -1,_A : bool = False,_A : Optional[TensorType] = None,): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = super(_A,self ).generate_dummy_inputs( _A,batch_size=_A,seq_length=_A,is_pair=_A,framework=_A ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE_ : Any = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = common_inputs["input_ids"].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE_ : List[str] = seqlen + 2 SCREAMING_SNAKE_CASE_ : Any = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE_ : Optional[int] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE_ : Optional[int] = common_inputs["attention_mask"] if self.use_past: SCREAMING_SNAKE_CASE_ : Tuple = ordered_inputs["attention_mask"].dtype SCREAMING_SNAKE_CASE_ : str = torch.cat( [ordered_inputs["attention_mask"], torch.ones(_A,_A,dtype=_A )],dim=1 ) return ordered_inputs @property def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" return 13
18
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, 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 UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self , lowercase , lowercase=2 , lowercase=56 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=2 , lowercase=7 , lowercase="gelu_new" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.0_2 , lowercase=4 , lowercase="block_sparse" , lowercase=True , lowercase=False , lowercase=2 , lowercase=3 , ) -> List[Any]: 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 lowerCamelCase_ = rescale_embeddings lowerCamelCase_ = attention_type lowerCamelCase_ = use_bias lowerCamelCase_ = block_size lowerCamelCase_ = num_random_blocks def SCREAMING_SNAKE_CASE_( self ) -> int: 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_ = BigBirdConfig( 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=lowercase , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: lowerCamelCase_ = self.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = config_and_inputs lowerCamelCase_ = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( snake_case_ , unittest.TestCase ): lowerCAmelCase__ = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) lowerCAmelCase__ = False lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE_( self ) -> Dict: lowerCamelCase_ = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE_( self ) -> int: super().test_hidden_states_output() @slow def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCamelCase_ = model_class_name.from_pretrained("google/bigbird-roberta-base" ) self.assertIsNotNone(lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: 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(lowercase , lowercase ) lowerCamelCase_ = model_class(lowercase ) @jax.jit def model_jitted(lowercase , lowercase=None , **lowercase ): return model(input_ids=lowercase , attention_mask=lowercase , **lowercase ) with self.subTest("JIT Enabled" ): lowerCamelCase_ = model_jitted(**lowercase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowerCamelCase_ = model_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase , lowercase=1e-5 , lowercase="outputs" , lowercase=None ) -> Optional[int]: # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version, # an effort was done to return `attention_probs` (yet to be verified). if name.startswith("outputs.attentions" ): return else: super().check_pt_flax_outputs(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
19
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed lowercase : Tuple = logging.getLogger(__name__) def _snake_case( SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__ = 10 , SCREAMING_SNAKE_CASE__ = 2 ) -> Union[str, Any]: def get_dataset(SCREAMING_SNAKE_CASE__ ): lowercase : Union[str, Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(SCREAMING_SNAKE_CASE__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) lowercase : Dict = get_dataset(SCREAMING_SNAKE_CASE__ ) lowercase : str = get_dataset(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) lowercase : str = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> int: lowercase : Dict = [] for epoch in range(SCREAMING_SNAKE_CASE__ ): # Train quickly model.train() for batch in dataloader: lowercase , lowercase : Tuple = batch lowercase : str = model(SCREAMING_SNAKE_CASE__ ) lowercase : int = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) accelerator.backward(SCREAMING_SNAKE_CASE__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class __snake_case ( nn.Module ): def __init__( self ): '''simple docstring''' super().__init__() lowercase : Optional[int] = nn.Parameter(torch.randn(1 ) ) lowercase : List[str] = nn.Parameter(torch.randn(1 ) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' return x * self.a + self.b class __snake_case ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) lowercase : Any = DummyModel() lowercase : List[Any] = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase , lowercase : int = dummy_dataloaders() lowercase : List[str] = ProjectConfiguration(total_limit=1 ,project_dir=snake_case ,automatic_checkpoint_naming=snake_case ) # Train baseline lowercase : Tuple = Accelerator(project_config=snake_case ) lowercase , lowercase , lowercase , lowercase : List[Any] = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) ,1 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) lowercase : Optional[Any] = DummyModel() lowercase : Any = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase , lowercase : Optional[Any] = dummy_dataloaders() # Train baseline lowercase : Tuple = Accelerator() lowercase , lowercase , lowercase , lowercase : List[str] = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ) # Save initial lowercase : List[str] = os.path.join(snake_case ,"""initial""" ) accelerator.save_state(snake_case ) ((lowercase) , (lowercase)) : Optional[Any] = model.a.item(), model.b.item() lowercase : Optional[int] = optimizer.state_dict() lowercase : Tuple = train(3 ,snake_case ,snake_case ,snake_case ,snake_case ) ((lowercase) , (lowercase)) : List[str] = model.a.item(), model.b.item() lowercase : List[str] = optimizer.state_dict() # Train partially set_seed(42 ) lowercase : Tuple = DummyModel() lowercase : Dict = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase , lowercase : Union[str, Any] = dummy_dataloaders() lowercase : Union[str, Any] = Accelerator() lowercase , lowercase , lowercase , lowercase : int = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ) accelerator.load_state(snake_case ) ((lowercase) , (lowercase)) : int = model.a.item(), model.b.item() lowercase : Optional[Any] = optimizer.state_dict() self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) lowercase : Any = train(2 ,snake_case ,snake_case ,snake_case ,snake_case ) # Save everything lowercase : List[Any] = os.path.join(snake_case ,"""checkpoint""" ) accelerator.save_state(snake_case ) # Load everything back in and make sure all states work accelerator.load_state(snake_case ) test_rands += train(1 ,snake_case ,snake_case ,snake_case ,snake_case ) ((lowercase) , (lowercase)) : int = model.a.item(), model.b.item() lowercase : List[str] = optimizer.state_dict() self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) lowercase : Dict = DummyModel() lowercase : List[Any] = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase , lowercase : Union[str, Any] = dummy_dataloaders() lowercase : Any = ProjectConfiguration(automatic_checkpoint_naming=snake_case ) # Train baseline lowercase : int = Accelerator(project_dir=snake_case ,project_config=snake_case ) lowercase , lowercase , lowercase , lowercase : Tuple = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ) # Save initial accelerator.save_state() ((lowercase) , (lowercase)) : Union[str, Any] = model.a.item(), model.b.item() lowercase : int = optimizer.state_dict() lowercase : Optional[Any] = train(3 ,snake_case ,snake_case ,snake_case ,snake_case ) ((lowercase) , (lowercase)) : Any = model.a.item(), model.b.item() lowercase : List[str] = optimizer.state_dict() # Train partially set_seed(42 ) lowercase : Optional[int] = DummyModel() lowercase : Union[str, Any] = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase , lowercase : Any = dummy_dataloaders() lowercase : Tuple = ProjectConfiguration(iteration=1 ,automatic_checkpoint_naming=snake_case ) lowercase : Tuple = Accelerator(project_dir=snake_case ,project_config=snake_case ) lowercase , lowercase , lowercase , lowercase : List[Any] = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ) accelerator.load_state(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_0""" ) ) ((lowercase) , (lowercase)) : Optional[int] = model.a.item(), model.b.item() lowercase : List[Any] = optimizer.state_dict() self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) lowercase : int = train(2 ,snake_case ,snake_case ,snake_case ,snake_case ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_1""" ) ) test_rands += train(1 ,snake_case ,snake_case ,snake_case ,snake_case ) ((lowercase) , (lowercase)) : Tuple = model.a.item(), model.b.item() lowercase : Optional[int] = optimizer.state_dict() self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = torch.tensor([1, 2, 3] ) lowercase : int = torch.tensor([2, 3, 4] ) lowercase : str = DummyModel() lowercase : Optional[Any] = torch.optim.Adam(net.parameters() ) lowercase : Any = Accelerator() with self.assertRaises(snake_case ) as ve: accelerator.register_for_checkpointing(snake_case ,snake_case ,snake_case ,snake_case ) lowercase : int = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) lowercase : Dict = DummyModel() lowercase : Optional[int] = torch.optim.Adam(params=model.parameters() ,lr=1e-3 ) lowercase : Union[str, Any] = torch.optim.lr_scheduler.StepLR(snake_case ,step_size=1 ,gamma=0.99 ) lowercase , lowercase : List[Any] = dummy_dataloaders() lowercase : List[str] = ProjectConfiguration(automatic_checkpoint_naming=snake_case ) # Train baseline lowercase : List[str] = Accelerator(project_dir=snake_case ,project_config=snake_case ) lowercase , lowercase , lowercase , lowercase , lowercase : Any = accelerator.prepare( snake_case ,snake_case ,snake_case ,snake_case ,snake_case ) # Save initial accelerator.save_state() lowercase : Optional[int] = scheduler.state_dict() train(3 ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ) self.assertNotEqual(snake_case ,scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_0""" ) ) self.assertEqual(snake_case ,scheduler.state_dict() ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) lowercase : Union[str, Any] = DummyModel() lowercase : Union[str, Any] = ProjectConfiguration(automatic_checkpoint_naming=snake_case ,total_limit=2 ) # Train baseline lowercase : Dict = Accelerator(project_dir=snake_case ,project_config=snake_case ) lowercase : Any = accelerator.prepare(snake_case ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(snake_case ,"""checkpoints""" ,"""checkpoint_10""" ) ) ) @require_cuda def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[Any] = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__ )] execute_subprocess_async(snake_case ,env=os.environ.copy() ) if __name__ == "__main__": lowercase : int = """/tmp/accelerate/state_checkpointing""" lowercase : List[str] = DummyModel() lowercase : Tuple = torch.optim.Adam(params=model.parameters(), lr=1e-3) lowercase : List[str] = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9) lowercase , lowercase : str = dummy_dataloaders() lowercase : str = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline lowercase : Tuple = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""") if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) lowercase , lowercase , lowercase , lowercase , lowercase : Optional[Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) lowercase , lowercase : Union[str, Any] = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: lowercase : Dict = group["""params"""][0].device break assert param_device.type == accelerator.device.type lowercase : int = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""") for group in optimizer.param_groups: lowercase : Tuple = group["""params"""][0].device break assert ( param_device.type == torch.device("""cpu""").type ), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""") for group in optimizer.param_groups: lowercase : List[str] = group["""params"""][0].device break assert ( param_device.type == accelerator.device.type ), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""): accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""") accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
20
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
from collections import defaultdict from math import gcd def UpperCamelCase_( lowerCamelCase_ = 150_0000 ) -> int: _lowercase : defaultdict = defaultdict(lowerCamelCase_ ) _lowercase : Tuple = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , lowerCamelCase_ , 2 ): if gcd(lowerCamelCase_ , lowerCamelCase_ ) > 1: continue _lowercase : Union[str, Any] = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(lowerCamelCase_ , limit + 1 , lowerCamelCase_ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F"{solution() = }")
21
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class A_ ( lowerCAmelCase_ ): @require_torch def lowercase ( self : str ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " _UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " _UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache _UpperCAmelCase = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(snake_case_ ) BertModel.from_pretrained(snake_case_ ) BertTokenizer.from_pretrained(snake_case_ ) pipeline(task="fill-mask" , model=snake_case_ ) # baseline - just load from_pretrained with normal network _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed _UpperCAmelCase = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCAmelCase = "1" _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def lowercase ( self : List[Any] ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " _UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " _UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache _UpperCAmelCase = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(snake_case_ ) BertModel.from_pretrained(snake_case_ ) BertTokenizer.from_pretrained(snake_case_ ) pipeline(task="fill-mask" , model=snake_case_ ) # baseline - just load from_pretrained with normal network _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed _UpperCAmelCase = self.get_env() _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCAmelCase = "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " _UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " _UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run] )] # should succeed _UpperCAmelCase = self.get_env() _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # next emulate no network _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCAmelCase = "1" _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def lowercase ( self : Optional[Any] ): _UpperCAmelCase = "\nfrom transformers import pipeline\n " _UpperCAmelCase = "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " _UpperCAmelCase = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " _UpperCAmelCase = self.get_env() _UpperCAmelCase = "1" _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, mock, run] )] _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode" , result.stderr.decode().replace("\n" , "" ) , ) @require_torch def lowercase ( self : Optional[int] ): _UpperCAmelCase = "\nfrom transformers import AutoModel\n " _UpperCAmelCase = "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network _UpperCAmelCase = [sys.executable, "-c", "\n".join([load, run] )] # should succeed _UpperCAmelCase = self.get_env() _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCAmelCase = "1" _UpperCAmelCase = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() )
22
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
'''simple docstring''' import os import sys import unittest UpperCamelCase__: int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path UpperCamelCase__: Optional[Any] = os.path.join(git_repo_path, "src", "transformers") UpperCamelCase__: List[Any] = "\n{0} = None\n" UpperCamelCase__: Optional[Any] = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" UpperCamelCase__: List[str] = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE( unittest.TestCase ): """simple docstring""" def A ( self : List[str] ) -> Optional[int]: UpperCAmelCase : int = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' ) self.assertIsNone(__snake_case ) UpperCAmelCase : List[Any] = find_backend(''' if not is_tokenizers_available():''' ) self.assertEqual(__snake_case , '''tokenizers''' ) UpperCAmelCase : Any = find_backend(''' if not is_tensorflow_text_available():''' ) self.assertEqual(__snake_case , '''tensorflow_text''' ) UpperCAmelCase : Union[str, Any] = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' ) self.assertEqual(__snake_case , '''sentencepiece_and_tokenizers''' ) UpperCAmelCase : Dict = find_backend( ''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' ) self.assertEqual(__snake_case , '''sentencepiece_and_tensorflow_text''' ) UpperCAmelCase : int = find_backend( ''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' ) self.assertEqual(__snake_case , '''sentencepiece_and_tokenizers_and_vision''' ) def A ( self : List[Any] ) -> Optional[int]: UpperCAmelCase : Optional[int] = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , __snake_case ) self.assertIn('''tensorflow_text''' , __snake_case ) self.assertIn('''sentencepiece_and_tokenizers''' , __snake_case ) # Likewise, we can't assert on the exact content of a key self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertModel''' , objects['''tf'''] ) self.assertIn('''FlaxBertModel''' , objects['''flax'''] ) self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertTokenizer''' , objects['''tensorflow_text'''] ) self.assertIn('''convert_slow_tokenizer''' , objects['''sentencepiece_and_tokenizers'''] ) def A ( self : Union[str, Any] ) -> str: UpperCAmelCase : List[Any] = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(__snake_case , '''\nCONSTANT = None\n''' ) UpperCAmelCase : Any = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( __snake_case , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) UpperCAmelCase : List[Any] = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') ''' UpperCAmelCase : Dict = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(__snake_case , __snake_case ) def A ( self : List[Any] ) -> Tuple: UpperCAmelCase : List[str] = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) ''' UpperCAmelCase : List[Any] = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , __snake_case )
23
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCamelCase__ ( ) -> Dict: raise RuntimeError('''CUDA out of memory.''' ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self : List[Any] ): """simple docstring""" super().__init__() __snake_case = nn.Linear(3 , 4 ) __snake_case = nn.BatchNormad(4 ) __snake_case = nn.Linear(4 , 5 ) def a (self : Optional[Any] , a__ : List[str] ): """simple docstring""" return self.lineara(self.batchnorm(self.lineara(a__ ) ) ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def a (self : Any ): """simple docstring""" __snake_case = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ : Any ): nonlocal batch_sizes batch_sizes.append(a__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(a__ , [128, 64, 32, 16, 8] ) def a (self : Tuple ): """simple docstring""" __snake_case = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ : str , a__ : Tuple ): nonlocal batch_sizes batch_sizes.append(a__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga __snake_case , __snake_case = mock_training_loop_function('''hello''' ) self.assertListEqual(a__ , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, '''hello'''] ) def a (self : List[Any] ): """simple docstring""" @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(a__ : Optional[int] ): pass with self.assertRaises(a__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def a (self : Tuple ): """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a__ : str ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(a__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def a (self : int ): """simple docstring""" @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ : int , a__ : Tuple , a__ : int ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(a__ ) as cm: mock_training_loop_function(128 , '''hello''' , '''world''' ) self.assertIn('''Batch size was passed into `f`''' , cm.exception.args[0] ) self.assertIn('''`f(arg1=\'hello\', arg2=\'world\')''' , cm.exception.args[0] ) def a (self : Optional[Any] ): """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a__ : Optional[Any] ): raise ValueError('''Oops, we had an error!''' ) with self.assertRaises(a__ ) as cm: mock_training_loop_function() self.assertIn('''Oops, we had an error!''' , cm.exception.args[0] ) @require_cuda def a (self : Union[str, Any] ): """simple docstring""" __snake_case = torch.cuda.memory_allocated() __snake_case = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , a__ ) __snake_case = release_memory(a__ ) self.assertEqual(torch.cuda.memory_allocated() , a__ )
24
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( '''The RoBERTa Model transformer with early exiting (DeeRoBERTa). ''' , a__ , ) class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : str = RobertaConfig __UpperCamelCase : Optional[Any] = '''roberta''' def __init__(self , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = RobertaEmbeddings(SCREAMING_SNAKE_CASE__ ) self.init_weights() @add_start_docstrings( '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. ''' , a__ , ) class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : List[Any] = RobertaConfig __UpperCamelCase : List[str] = '''roberta''' def __init__(self , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = config.num_labels SCREAMING_SNAKE_CASE__ : Tuple = config.num_hidden_layers SCREAMING_SNAKE_CASE__ : int = DeeRobertaModel(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = nn.Dropout(config.hidden_dropout_prob ) SCREAMING_SNAKE_CASE__ : Tuple = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , 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__=-1 , SCREAMING_SNAKE_CASE__=False , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.num_layers try: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.roberta( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , position_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ , inputs_embeds=SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[str] = outputs[1] SCREAMING_SNAKE_CASE__ : str = self.dropout(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.classifier(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: SCREAMING_SNAKE_CASE__ : Optional[Any] = e.message SCREAMING_SNAKE_CASE__ : Optional[int] = e.exit_layer SCREAMING_SNAKE_CASE__ : Any = outputs[0] if not self.training: SCREAMING_SNAKE_CASE__ : List[Any] = entropy(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] if labels is not None: if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE__ : Union[str, Any] = MSELoss() SCREAMING_SNAKE_CASE__ : Optional[Any] = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits SCREAMING_SNAKE_CASE__ : List[Any] = [] for highway_exit in outputs[-1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = highway_exit[0] if not self.training: highway_logits_all.append(SCREAMING_SNAKE_CASE__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE__ : Any = MSELoss() SCREAMING_SNAKE_CASE__ : Any = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE__ : Any = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ : str = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(SCREAMING_SNAKE_CASE__ ) if train_highway: SCREAMING_SNAKE_CASE__ : str = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: SCREAMING_SNAKE_CASE__ : List[str] = (loss,) + outputs if not self.training: SCREAMING_SNAKE_CASE__ : str = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: SCREAMING_SNAKE_CASE__ : str = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
25
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
import enum import shutil import sys _snake_case , _snake_case = shutil.get_terminal_size() _snake_case = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} class lowercase ( enum.Enum ): _a = 0 _a = 1 def lowerCAmelCase_ ( snake_case_,snake_case_="" ): sys.stdout.write(str(snake_case_ ) + end ) sys.stdout.flush() def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_="" ): forceWrite(f'''\u001b[{color}m{content}\u001b[0m''',snake_case_ ) def lowerCAmelCase_ ( ): forceWrite("""\r""" ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): forceWrite(f'''\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}''' ) def lowerCAmelCase_ ( ): forceWrite(""" """ * TERMINAL_WIDTH ) reset_cursor() def lowerCAmelCase_ ( ): reset_cursor() forceWrite("""-""" * TERMINAL_WIDTH )
26
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "naver-clova-ix/donut-base-finetuned-docvqa" A_ = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) A_ = "document_qa" A_ = AutoProcessor A_ = VisionEncoderDecoderModel A_ = ["image", "text"] A_ = ["text"] def __init__( self , *__a , **__a ): '''simple docstring''' if not is_vision_available(): raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.' ) super().__init__(*__a , **__a ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : List[str] = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' __a : Any = task_prompt.replace('{user_input}' , __a ) __a : Optional[Any] = self.pre_processor.tokenizer( __a , add_special_tokens=__a , return_tensors='pt' ).input_ids __a : Optional[int] = self.pre_processor(__a , return_tensors='pt' ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.model.generate( inputs['pixel_values'].to(self.device ) , decoder_input_ids=inputs['decoder_input_ids'].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__a , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__a , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__a , ).sequences def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = self.pre_processor.batch_decode(__a )[0] __a : str = sequence.replace(self.pre_processor.tokenizer.eos_token , '' ) __a : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , '' ) __a : Any = re.sub(r'<.*?>' , '' , __a , count=1 ).strip() # remove first task start token __a : Tuple = self.pre_processor.tokenajson(__a ) return sequence["answer"]
27
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def A ( self : int , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : Optional[int] ): """simple docstring""" UpperCamelCase = hf_hub_download( repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) UpperCamelCase = VideoClassificationPipeline(model=UpperCamelCase__ , image_processor=UpperCamelCase__ , top_k=2 ) UpperCamelCase = [ example_video_filepath, 'https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4', ] return video_classifier, examples def A ( self : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any ): """simple docstring""" for example in examples: UpperCamelCase = video_classifier(UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {'score': ANY(UpperCamelCase__ ), 'label': ANY(UpperCamelCase__ )}, {'score': ANY(UpperCamelCase__ ), 'label': ANY(UpperCamelCase__ )}, ] , ) @require_torch def A ( self : Any ): """simple docstring""" UpperCamelCase = 'hf-internal-testing/tiny-random-VideoMAEForVideoClassification' UpperCamelCase = VideoMAEFeatureExtractor( size={'shortest_edge': 1_0} , crop_size={'height': 1_0, 'width': 1_0} ) UpperCamelCase = pipeline( 'video-classification' , model=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , frame_sampling_rate=4 ) UpperCamelCase = hf_hub_download(repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) UpperCamelCase = video_classifier(UpperCamelCase__ , top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=4 ) , [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}] , ) UpperCamelCase = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=4 ) , [ [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], ] , ) @require_tf def A ( self : List[Any] ): """simple docstring""" pass
28
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder __UpperCAmelCase = datasets.utils.logging.get_logger(__name__) class lowerCamelCase (folder_based_builder.FolderBasedBuilderConfig ): '''simple docstring''' _snake_case : bool = None _snake_case : bool = None class lowerCamelCase (folder_based_builder.FolderBasedBuilder ): '''simple docstring''' _snake_case : int = datasets.Audio() _snake_case : Optional[int] = '''audio''' _snake_case : int = AudioFolderConfig _snake_case : List[str] # definition at the bottom of the script _snake_case : Dict = AudioClassification(audio_column='''audio''' , label_column='''label''' ) __UpperCAmelCase = [ '.aiff', '.au', '.avr', '.caf', '.flac', '.htk', '.svx', '.mat4', '.mat5', '.mpc2k', '.ogg', '.paf', '.pvf', '.raw', '.rf64', '.sd2', '.sds', '.ircam', '.voc', '.w64', '.wav', '.nist', '.wavex', '.wve', '.xi', '.mp3', '.opus', ] __UpperCAmelCase = AUDIO_EXTENSIONS
29
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
def a ( snake_case__: int ): '''simple docstring''' if num <= 0: raise ValueError('''Input must be a positive integer''' ) lowercase_ = [True] * (num + 1) lowercase_ = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , snake_case__ ): lowercase_ = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() __a = int(input('Enter a positive integer: ').strip()) print(prime_sieve_eratosthenes(user_num))
30
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = ["""bert-base-uncased""", """bert-base-cased"""] __SCREAMING_SNAKE_CASE : List[str] = """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class lowerCamelCase_ (tf.keras.Model ): '''simple docstring''' def __init__( self : Union[str, Any] , A : Tuple ): super().__init__() _UpperCAmelCase : Any = tokenizer _UpperCAmelCase : int = AutoConfig.from_pretrained(A ) _UpperCAmelCase : str = TFAutoModel.from_config(A ) def _A ( self : Union[str, Any] , A : Dict ): _UpperCAmelCase : Any = self.tokenizer(A ) _UpperCAmelCase : Union[str, Any] = self.bert(**A ) return out["pooler_output"] @require_tf @require_tensorflow_text class lowerCamelCase_ (unittest.TestCase ): '''simple docstring''' def _A ( self : List[str] ): super().setUp() _UpperCAmelCase : Union[str, Any] = [ BertTokenizer.from_pretrained(A ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false _UpperCAmelCase : List[Any] = [TFBertTokenizer.from_pretrained(A ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(A , use_fast_bert_tokenizer=A ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) _UpperCAmelCase : Dict = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] _UpperCAmelCase : str = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _A ( self : Optional[Any] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): _UpperCAmelCase : Any = tokenizer(A , return_tensors="tf" , padding="longest" ) _UpperCAmelCase : str = tf_tokenizer(A ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _A ( self : int ): for tf_tokenizer in self.tf_tokenizers: _UpperCAmelCase : str = tf_tokenizer(self.paired_sentences ) _UpperCAmelCase : int = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _A ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: _UpperCAmelCase : List[Any] = tf.function(A ) for test_inputs in (self.test_sentences, self.paired_sentences): _UpperCAmelCase : int = tf.constant(A ) _UpperCAmelCase : Optional[Any] = compiled_tokenizer(A ) _UpperCAmelCase : int = tf_tokenizer(A ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _A ( self : List[Any] ): for tf_tokenizer in self.tf_tokenizers: _UpperCAmelCase : Any = ModelToSave(tokenizer=A ) _UpperCAmelCase : Optional[int] = tf.convert_to_tensor(self.test_sentences ) _UpperCAmelCase : Optional[Any] = model(A ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: _UpperCAmelCase : Union[str, Any] = Path(A ) / "saved.model" model.save(A ) _UpperCAmelCase : Dict = tf.keras.models.load_model(A ) _UpperCAmelCase : str = loaded_model(A ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
31
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
from __future__ import annotations import math def SCREAMING_SNAKE_CASE_ ( __A : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True UpperCAmelCase_ : Dict = [num for num in range(3, 10_0001, 2) if not is_prime(num)] def SCREAMING_SNAKE_CASE_ ( __A : int ) -> list[int]: """simple docstring""" if not isinstance(__A , __A ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) a_ : Any = [] for num in range(len(__A ) ): a_ : str = 0 while 2 * i * i <= odd_composites[num]: a_ : Any = odd_composites[num] - 2 * i * i if is_prime(__A ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(__A ) == n: return list_nums return [] def SCREAMING_SNAKE_CASE_ ( ) -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F'{solution() = }')
32
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class _UpperCAmelCase ( unittest.TestCase ): def __init__( self : Dict , A : List[Any] , A : Tuple=7 , A : Dict=3 , A : Optional[Any]=18 , A : Union[str, Any]=30 , A : List[str]=4_00 , A : List[Any]=True , A : Union[str, Any]=32 , A : Any=True , ) -> List[Any]: lowercase_ : Optional[Any] = parent lowercase_ : Optional[int] = batch_size lowercase_ : Any = num_channels lowercase_ : List[str] = image_size lowercase_ : Optional[int] = min_resolution lowercase_ : Dict = max_resolution lowercase_ : str = do_resize lowercase_ : Optional[Any] = size_divisor lowercase_ : List[Any] = do_rescale def A ( self : Dict ) -> Optional[int]: return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class _UpperCAmelCase ( _A , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : List[Any] = GLPNImageProcessor if is_vision_available() else None def A ( self : Union[str, Any] ) -> List[str]: lowercase_ : Any = GLPNImageProcessingTester(self ) @property def A ( self : int ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> int: lowercase_ : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , '''do_resize''' ) ) self.assertTrue(hasattr(A , '''size_divisor''' ) ) self.assertTrue(hasattr(A , '''resample''' ) ) self.assertTrue(hasattr(A , '''do_rescale''' ) ) def A ( self : Any ) -> str: pass def A ( self : Tuple ) -> Tuple: # Initialize image_processing lowercase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowercase_ : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def A ( self : List[Any] ) -> Tuple: # Initialize image_processing lowercase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , numpify=A ) for image in image_inputs: self.assertIsInstance(A , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowercase_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def A ( self : Optional[int] ) -> List[Any]: # Initialize image_processing lowercase_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowercase_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
33
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
'''simple docstring''' from __future__ import annotations def snake_case_ (_a : float , _a : float , _a : float , ): if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative in a semiconductor''' ) elif hole_conc < 0: raise ValueError('''Hole concentration cannot be negative in a semiconductor''' ) elif intrinsic_conc < 0: raise ValueError( '''Intrinsic concentration cannot be negative in a semiconductor''' ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
34
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( "stable diffusion controlnet", "0.22.0", "Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.", standard_warn=False, stacklevel=3, )
35
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class UpperCAmelCase_ ( unittest.TestCase): def __init__( self, __a, __a=7, __a=3, __a=30, __a=400, __a=True, __a=None, __a=True, __a=1 / 255, __a=True, __a=[0.5, 0.5, 0.5], __a=[0.5, 0.5, 0.5], __a=True, ): '''simple docstring''' _lowerCAmelCase : int = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} _lowerCAmelCase : Dict = parent _lowerCAmelCase : Optional[int] = batch_size _lowerCAmelCase : Tuple = num_channels _lowerCAmelCase : Any = min_resolution _lowerCAmelCase : Tuple = max_resolution _lowerCAmelCase : Optional[Any] = do_resize _lowerCAmelCase : Any = size _lowerCAmelCase : Union[str, Any] = do_rescale _lowerCAmelCase : List[Any] = rescale_factor _lowerCAmelCase : Tuple = do_normalize _lowerCAmelCase : Union[str, Any] = image_mean _lowerCAmelCase : Tuple = image_std _lowerCAmelCase : Tuple = do_pad def snake_case__ ( self): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def snake_case__ ( self, __a, __a=False): '''simple docstring''' if not batched: _lowerCAmelCase : List[str] = image_inputs[0] if isinstance(__a, Image.Image): _lowerCAmelCase , _lowerCAmelCase : List[str] = image.size else: _lowerCAmelCase , _lowerCAmelCase : List[Any] = image.shape[1], image.shape[2] if w < h: _lowerCAmelCase : Optional[int] = int(self.size["shortest_edge"] * h / w) _lowerCAmelCase : List[Any] = self.size["shortest_edge"] elif w > h: _lowerCAmelCase : str = self.size["shortest_edge"] _lowerCAmelCase : Union[str, Any] = int(self.size["shortest_edge"] * w / h) else: _lowerCAmelCase : Any = self.size["shortest_edge"] _lowerCAmelCase : List[str] = self.size["shortest_edge"] else: _lowerCAmelCase : Optional[int] = [] for image in image_inputs: _lowerCAmelCase , _lowerCAmelCase : List[str] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) _lowerCAmelCase : List[str] = max(__a, key=lambda __a: item[0])[0] _lowerCAmelCase : Union[str, Any] = max(__a, key=lambda __a: item[1])[1] return expected_height, expected_width @require_torch @require_vision class UpperCAmelCase_ ( a , unittest.TestCase): lowerCamelCase__ = DetrImageProcessor if is_vision_available() else None def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[Any] = DetrImageProcessingTester(self) @property def snake_case__ ( self): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : str = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a, "image_mean")) self.assertTrue(hasattr(__a, "image_std")) self.assertTrue(hasattr(__a, "do_normalize")) self.assertTrue(hasattr(__a, "do_rescale")) self.assertTrue(hasattr(__a, "rescale_factor")) self.assertTrue(hasattr(__a, "do_resize")) self.assertTrue(hasattr(__a, "size")) self.assertTrue(hasattr(__a, "do_pad")) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"shortest_edge": 18, "longest_edge": 1333}) self.assertEqual(image_processor.do_pad, __a) _lowerCAmelCase : int = self.image_processing_class.from_dict( self.image_processor_dict, size=42, max_size=84, pad_and_return_pixel_mask=__a) self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84}) self.assertEqual(image_processor.do_pad, __a) def snake_case__ ( self): '''simple docstring''' pass def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Any = self.image_processing_class(**self.image_processor_dict) # create random PIL images _lowerCAmelCase : List[str] = prepare_image_inputs(self.image_processor_tester, equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a, Image.Image) # Test not batched input _lowerCAmelCase : Tuple = image_processing(image_inputs[0], return_tensors="pt").pixel_values _lowerCAmelCase , _lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowerCAmelCase , _lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(__a, batched=__a) _lowerCAmelCase : Optional[Any] = image_processing(__a, return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors _lowerCAmelCase : int = prepare_image_inputs(self.image_processor_tester, equal_resolution=__a, numpify=__a) for image in image_inputs: self.assertIsInstance(__a, np.ndarray) # Test not batched input _lowerCAmelCase : List[str] = image_processing(image_inputs[0], return_tensors="pt").pixel_values _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowerCAmelCase : List[Any] = image_processing(__a, return_tensors="pt").pixel_values _lowerCAmelCase , _lowerCAmelCase : int = self.image_processor_tester.get_expected_values(__a, batched=__a) self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors _lowerCAmelCase : Any = prepare_image_inputs(self.image_processor_tester, equal_resolution=__a, torchify=__a) for image in image_inputs: self.assertIsInstance(__a, torch.Tensor) # Test not batched input _lowerCAmelCase : Optional[Any] = image_processing(image_inputs[0], return_tensors="pt").pixel_values _lowerCAmelCase , _lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(__a) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowerCAmelCase : Any = image_processing(__a, return_tensors="pt").pixel_values _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.image_processor_tester.get_expected_values(__a, batched=__a) self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) @slow def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f: _lowerCAmelCase : int = json.loads(f.read()) _lowerCAmelCase : Optional[int] = {"image_id": 3_9769, "annotations": target} # encode them _lowerCAmelCase : str = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50") _lowerCAmelCase : str = image_processing(images=__a, annotations=__a, return_tensors="pt") # verify pixel values _lowerCAmelCase : Optional[Any] = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["pixel_values"].shape, __a) _lowerCAmelCase : Union[str, Any] = torch.tensor([0.2_796, 0.3_138, 0.3_481]) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], __a, atol=1E-4)) # verify area _lowerCAmelCase : int = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438]) self.assertTrue(torch.allclose(encoding["labels"][0]["area"], __a)) # verify boxes _lowerCAmelCase : Union[str, Any] = torch.Size([6, 4]) self.assertEqual(encoding["labels"][0]["boxes"].shape, __a) _lowerCAmelCase : int = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215]) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], __a, atol=1E-3)) # verify image_id _lowerCAmelCase : List[str] = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], __a)) # verify is_crowd _lowerCAmelCase : int = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], __a)) # verify class_labels _lowerCAmelCase : List[str] = torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], __a)) # verify orig_size _lowerCAmelCase : Optional[int] = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], __a)) # verify size _lowerCAmelCase : Any = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["labels"][0]["size"], __a)) @slow def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f: _lowerCAmelCase : Union[str, Any] = json.loads(f.read()) _lowerCAmelCase : Tuple = {"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target} _lowerCAmelCase : Optional[Any] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic") # encode them _lowerCAmelCase : Optional[Any] = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic") _lowerCAmelCase : str = image_processing(images=__a, annotations=__a, masks_path=__a, return_tensors="pt") # verify pixel values _lowerCAmelCase : Optional[Any] = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["pixel_values"].shape, __a) _lowerCAmelCase : str = torch.tensor([0.2_796, 0.3_138, 0.3_481]) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], __a, atol=1E-4)) # verify area _lowerCAmelCase : List[Any] = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147]) self.assertTrue(torch.allclose(encoding["labels"][0]["area"], __a)) # verify boxes _lowerCAmelCase : Union[str, Any] = torch.Size([6, 4]) self.assertEqual(encoding["labels"][0]["boxes"].shape, __a) _lowerCAmelCase : List[str] = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625]) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], __a, atol=1E-3)) # verify image_id _lowerCAmelCase : List[str] = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], __a)) # verify is_crowd _lowerCAmelCase : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], __a)) # verify class_labels _lowerCAmelCase : int = torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], __a)) # verify masks _lowerCAmelCase : Dict = 82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item(), __a) # verify orig_size _lowerCAmelCase : Tuple = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], __a)) # verify size _lowerCAmelCase : Tuple = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["labels"][0]["size"], __a))
36
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
'''simple docstring''' from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """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 , UpperCamelCase , UpperCamelCase , UpperCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCamelCase , UpperCamelCase , UpperCamelCase ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , UpperCamelCase , UpperCamelCase , UpperCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCamelCase , UpperCamelCase , UpperCamelCase ) , ) ) def _SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowerCAmelCase__ : Tuple = [90, 23, 6, 33, 21, 65, 123, 34423] lowerCAmelCase__ : Optional[int] = math.log(len(UpperCamelCase ) , 2 ) print(f"""Optimal value : {minimax(0 , 0 , UpperCamelCase , UpperCamelCase , UpperCamelCase )}""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
37
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : str ) -> int: """simple docstring""" with open(__magic_name__ ) as metadata_file: UpperCamelCase :int = json.load(__magic_name__ ) UpperCamelCase :List[Any] = LukeConfig(use_entity_aware_attention=__magic_name__ , **metadata["""model_config"""] ) # Load in the weights from the checkpoint_path UpperCamelCase :List[str] = torch.load(__magic_name__ , map_location="""cpu""" )["""module"""] # Load the entity vocab file UpperCamelCase :Optional[int] = load_original_entity_vocab(__magic_name__ ) # add an entry for [MASK2] UpperCamelCase :Optional[Any] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase :Any = XLMRobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase :Union[str, Any] = AddedToken("""<ent>""" , lstrip=__magic_name__ , rstrip=__magic_name__ ) UpperCamelCase :Optional[int] = AddedToken("""<ent2>""" , lstrip=__magic_name__ , rstrip=__magic_name__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"""Saving tokenizer to {pytorch_dump_folder_path}""" ) tokenizer.save_pretrained(__magic_name__ ) with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """r""" ) as f: UpperCamelCase :str = json.load(__magic_name__ ) UpperCamelCase :Optional[int] = """MLukeTokenizer""" with open(os.path.join(__magic_name__ , """tokenizer_config.json""" ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) with open(os.path.join(__magic_name__ , MLukeTokenizer.vocab_files_names["""entity_vocab_file"""] ) , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) UpperCamelCase :Optional[int] = MLukeTokenizer.from_pretrained(__magic_name__ ) # Initialize the embeddings of the special tokens UpperCamelCase :str = tokenizer.convert_tokens_to_ids(["""@"""] )[0] UpperCamelCase :Optional[int] = tokenizer.convert_tokens_to_ids(["""#"""] )[0] UpperCamelCase :str = state_dict["""embeddings.word_embeddings.weight"""] UpperCamelCase :int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase :Dict = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase :Union[str, Any] = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase :Dict = state_dict[bias_name] UpperCamelCase :str = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase :Dict = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase :Optional[int] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase :str = f"""encoder.layer.{layer_index}.attention.self.""" UpperCamelCase :str = state_dict[prefix + matrix_name] UpperCamelCase :Any = state_dict[prefix + matrix_name] UpperCamelCase :List[Any] = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase :int = state_dict["""entity_embeddings.entity_embeddings.weight"""] UpperCamelCase :Dict = entity_emb[entity_vocab["""[MASK]"""]].unsqueeze(0 ) UpperCamelCase :int = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase :Union[str, Any] = state_dict["""entity_predictions.bias"""] UpperCamelCase :List[Any] = entity_prediction_bias[entity_vocab["""[MASK]"""]].unsqueeze(0 ) UpperCamelCase :Dict = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase :Union[str, Any] = LukeForMaskedLM(config=__magic_name__ ).eval() state_dict.pop("""entity_predictions.decoder.weight""" ) state_dict.pop("""lm_head.decoder.weight""" ) state_dict.pop("""lm_head.decoder.bias""" ) UpperCamelCase :int = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("""lm_head""" ) or key.startswith("""entity_predictions""" )): UpperCamelCase :Union[str, Any] = state_dict[key] else: UpperCamelCase :Optional[Any] = state_dict[key] UpperCamelCase , UpperCamelCase :List[Any] = model.load_state_dict(__magic_name__ , strict=__magic_name__ ) if set(__magic_name__ ) != {"luke.embeddings.position_ids"}: raise ValueError(f"""Unexpected unexpected_keys: {unexpected_keys}""" ) if set(__magic_name__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f"""Unexpected missing_keys: {missing_keys}""" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase :Dict = MLukeTokenizer.from_pretrained(__magic_name__ , task="""entity_classification""" ) UpperCamelCase :Dict = """ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).""" UpperCamelCase :Union[str, Any] = (0, 9) UpperCamelCase :Optional[Any] = tokenizer(__magic_name__ , entity_spans=[span] , return_tensors="""pt""" ) UpperCamelCase :Union[str, Any] = model(**__magic_name__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase :Union[str, Any] = torch.Size((1, 33, 768) ) UpperCamelCase :Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase :Union[str, Any] = torch.Size((1, 1, 768) ) UpperCamelCase :Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is""" f""" {expected_shape}""" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __magic_name__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase :Dict = MLukeTokenizer.from_pretrained(__magic_name__ ) UpperCamelCase :Optional[int] = """Tokyo is the capital of <mask>.""" UpperCamelCase :Optional[int] = (24, 30) UpperCamelCase :Optional[Any] = tokenizer(__magic_name__ , entity_spans=[span] , return_tensors="""pt""" ) UpperCamelCase :List[str] = model(**__magic_name__ ) UpperCamelCase :Optional[Any] = encoding["""input_ids"""][0].tolist() UpperCamelCase :Any = input_ids.index(tokenizer.convert_tokens_to_ids("""<mask>""" ) ) UpperCamelCase :str = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__magic_name__ ) UpperCamelCase :Tuple = outputs.entity_logits[0][0].argmax().item() UpperCamelCase :str = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("""en:""" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("""Saving PyTorch model to {}""".format(__magic_name__ ) ) model.save_pretrained(__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = ["""[MASK]""", """[PAD]""", """[UNK]"""] UpperCamelCase :Dict = [json.loads(__magic_name__ ) for line in open(__magic_name__ )] UpperCamelCase :int = {} for entry in data: UpperCamelCase :Dict = entry["""id"""] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase :int = entity_id break UpperCamelCase :Dict = f"""{language}:{entity_name}""" UpperCamelCase :Optional[int] = entity_id return new_mapping if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Path to a pytorch_model.bin file.''') parser.add_argument( '''--metadata_path''', default=None, type=str, help='''Path to a metadata.json file, defining the configuration.''' ) parser.add_argument( '''--entity_vocab_path''', default=None, type=str, help='''Path to an entity_vocab.tsv file, containing the entity vocabulary.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to where to dump the output PyTorch model.''' ) parser.add_argument( '''--model_size''', default='''base''', type=str, choices=['''base''', '''large'''], help='''Size of the model to be converted.''' ) UpperCAmelCase_ : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
38
'''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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder _a = '''__DUMMY_TRANSFORMERS_USER__''' _a = '''Dummy User''' _a = '''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''' _a = '''https://hub-ci.huggingface.co''' _a = CI_HUB_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}''' _a = CI_HUB_ENDPOINT + '''/{repo_id}/resolve/{revision}/{filename}''' _a = Path('''~/.huggingface/hub_ci_token''').expanduser() @pytest.fixture def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" monkeypatch.setattr( 'huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE' , __lowerCAmelCase ) @pytest.fixture def __A ( __lowerCAmelCase )-> Union[str, Any]: """simple docstring""" monkeypatch.setattr('datasets.config.HF_ENDPOINT' , __lowerCAmelCase ) monkeypatch.setattr('datasets.config.HUB_DATASETS_URL' , __lowerCAmelCase ) @pytest.fixture def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" monkeypatch.setattr('huggingface_hub.hf_api.HfFolder.path_token' , __lowerCAmelCase ) @pytest.fixture def __A ( __lowerCAmelCase , __lowerCAmelCase )-> Tuple: """simple docstring""" HfFolder.save_token(__lowerCAmelCase ) yield HfFolder.delete_token() @pytest.fixture(scope='session' ) def __A ( )-> Tuple: """simple docstring""" return HfApi(endpoint=__lowerCAmelCase ) @pytest.fixture(scope='session' ) def __A ( __lowerCAmelCase )-> Union[str, Any]: """simple docstring""" _UpperCAmelCase = HfFolder.get_token() HfFolder.save_token(__lowerCAmelCase ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(__lowerCAmelCase ) @pytest.fixture def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" def _cleanup_repo(__lowerCAmelCase ): hf_api.delete_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' ) return _cleanup_repo @pytest.fixture def __A ( __lowerCAmelCase )-> Union[str, Any]: """simple docstring""" @contextmanager def _temporary_repo(__lowerCAmelCase ): try: yield repo_id finally: cleanup_repo(__lowerCAmelCase ) return _temporary_repo @pytest.fixture(scope='session' ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Dict: """simple docstring""" _UpperCAmelCase = F"""repo_txt_data-{int(time.time() * 10E3 )}""" _UpperCAmelCase = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' , private=__lowerCAmelCase ) hf_api.upload_file( token=__lowerCAmelCase , path_or_fileobj=str(__lowerCAmelCase ) , path_in_repo='data/text_data.txt' , repo_id=__lowerCAmelCase , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> List[Any]: """simple docstring""" return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='session' ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> int: """simple docstring""" _UpperCAmelCase = F"""repo_zipped_txt_data-{int(time.time() * 10E3 )}""" _UpperCAmelCase = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' , private=__lowerCAmelCase ) hf_api.upload_file( token=__lowerCAmelCase , path_or_fileobj=str(__lowerCAmelCase ) , path_in_repo='data.zip' , repo_id=__lowerCAmelCase , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> List[Any]: """simple docstring""" return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='session' ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Dict: """simple docstring""" _UpperCAmelCase = F"""repo_zipped_img_data-{int(time.time() * 10E3 )}""" _UpperCAmelCase = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' , private=__lowerCAmelCase ) hf_api.upload_file( token=__lowerCAmelCase , path_or_fileobj=str(__lowerCAmelCase ) , path_in_repo='data.zip' , repo_id=__lowerCAmelCase , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(__lowerCAmelCase , token=__lowerCAmelCase , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> int: """simple docstring""" return hf_private_dataset_repo_zipped_img_data_
39
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" import random def lowercase ( A_ , A_ )-> tuple: '''simple docstring''' a , a , a : List[str] = [], [], [] for element in data: if element < pivot: less.append(A_ ) elif element > pivot: greater.append(A_ ) else: equal.append(A_ ) return less, equal, greater def lowercase ( A_ , A_ )-> Dict: '''simple docstring''' if index >= len(A_ ) or index < 0: return None a : Optional[Any] = items[random.randint(0 , len(A_ ) - 1 )] a : int = 0 a , a , a : Any = _partition(A_ , A_ ) a : Union[str, Any] = len(A_ ) a : Any = len(A_ ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(A_ , A_ ) # must be in larger else: return quick_select(A_ , index - (m + count) )
40
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, 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 UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
'''simple docstring''' # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class _lowercase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): a = StableDiffusionControlNetImgaImgPipeline a = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} a = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS a = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"""control_image"""} ) a = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase_ ( self: Any ): torch.manual_seed(0 ) lowerCamelCase__ : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) lowerCamelCase__ : List[Any] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) lowerCamelCase__ : List[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=UpperCamelCase__ , set_alpha_to_one=UpperCamelCase__ , ) torch.manual_seed(0 ) lowerCamelCase__ : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase__ : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) lowerCamelCase__ : str = CLIPTextModel(UpperCamelCase__ ) lowerCamelCase__ : Any = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) lowerCamelCase__ : Dict = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCamelCase_ ( self: str , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple=0 ): if str(UpperCamelCase__ ).startswith("""mps""" ): lowerCamelCase__ : Any = torch.manual_seed(UpperCamelCase__ ) else: lowerCamelCase__ : int = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) lowerCamelCase__ : Tuple = 2 lowerCamelCase__ : Optional[Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCamelCase__ , device=torch.device(UpperCamelCase__ ) , ) lowerCamelCase__ : Optional[Any] = floats_tensor(control_image.shape , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) lowerCamelCase__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase__ : List[str] = Image.fromarray(np.uinta(UpperCamelCase__ ) ).convert("""RGB""" ).resize((64, 64) ) lowerCamelCase__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def lowerCamelCase_ ( self: Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCamelCase_ ( self: Optional[int] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def lowerCamelCase_ ( self: Any ): self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = StableDiffusionControlNetImgaImgPipeline a = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} a = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS a = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def lowerCamelCase_ ( self: str ): torch.manual_seed(0 ) lowerCamelCase__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCamelCase__: Tuple ): if isinstance(UpperCamelCase__ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) lowerCamelCase__ : Optional[Any] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCamelCase__ ) torch.manual_seed(0 ) lowerCamelCase__ : Tuple = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCamelCase__ ) torch.manual_seed(0 ) lowerCamelCase__ : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=UpperCamelCase__ , set_alpha_to_one=UpperCamelCase__ , ) torch.manual_seed(0 ) lowerCamelCase__ : List[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase__ : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) lowerCamelCase__ : Optional[int] = CLIPTextModel(UpperCamelCase__ ) lowerCamelCase__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) lowerCamelCase__ : Any = MultiControlNetModel([controlneta, controlneta] ) lowerCamelCase__ : List[Any] = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any]=0 ): if str(UpperCamelCase__ ).startswith("""mps""" ): lowerCamelCase__ : int = torch.manual_seed(UpperCamelCase__ ) else: lowerCamelCase__ : Optional[Any] = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) lowerCamelCase__ : Any = 2 lowerCamelCase__ : List[str] = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCamelCase__ , device=torch.device(UpperCamelCase__ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCamelCase__ , device=torch.device(UpperCamelCase__ ) , ), ] lowerCamelCase__ : Tuple = floats_tensor(control_image[0].shape , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) lowerCamelCase__ : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase__ : Any = Image.fromarray(np.uinta(UpperCamelCase__ ) ).convert("""RGB""" ).resize((64, 64) ) lowerCamelCase__ : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : str = self.get_dummy_components() lowerCamelCase__ : List[str] = self.pipeline_class(**UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = 10.0 lowerCamelCase__ : Any = 4 lowerCamelCase__ : Union[str, Any] = self.get_dummy_inputs(UpperCamelCase__ ) lowerCamelCase__ : List[str] = steps lowerCamelCase__ : Optional[int] = scale lowerCamelCase__ : Union[str, Any] = pipe(**UpperCamelCase__ )[0] lowerCamelCase__ : Any = self.get_dummy_inputs(UpperCamelCase__ ) lowerCamelCase__ : Any = steps lowerCamelCase__ : Union[str, Any] = scale lowerCamelCase__ : Tuple = pipe(**UpperCamelCase__ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] lowerCamelCase__ : str = self.get_dummy_inputs(UpperCamelCase__ ) lowerCamelCase__ : Tuple = steps lowerCamelCase__ : int = scale lowerCamelCase__ : List[str] = pipe(**UpperCamelCase__ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] lowerCamelCase__ : Optional[Any] = self.get_dummy_inputs(UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = steps lowerCamelCase__ : Optional[Any] = scale lowerCamelCase__ : Optional[Any] = pipe(**UpperCamelCase__ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def lowerCamelCase_ ( self: str ): return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCamelCase_ ( self: int ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def lowerCamelCase_ ( self: int ): self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Optional[Any] = self.get_dummy_components() lowerCamelCase__ : str = self.pipeline_class(**UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCamelCase__ ) except NotImplementedError: pass @slow @require_torch_gpu class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: List[str] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) lowerCamelCase__ : Tuple = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , safety_checker=UpperCamelCase__ , controlnet=UpperCamelCase__ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCamelCase__ ) lowerCamelCase__ : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) lowerCamelCase__ : List[Any] = """evil space-punk bird""" lowerCamelCase__ : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((512, 512) ) lowerCamelCase__ : Union[str, Any] = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((512, 512) ) lowerCamelCase__ : Optional[int] = pipe( UpperCamelCase__ , UpperCamelCase__ , control_image=UpperCamelCase__ , generator=UpperCamelCase__ , output_type="""np""" , num_inference_steps=50 , strength=0.6 , ) lowerCamelCase__ : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) lowerCamelCase__ : Optional[int] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9e-2
41
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase ( _lowerCamelCase , unittest.TestCase ): __lowercase = LDMTextToImagePipeline __lowercase = TEXT_TO_IMAGE_PARAMS - { """negative_prompt""", """negative_prompt_embeds""", """cross_attention_kwargs""", """prompt_embeds""", } __lowercase = PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """callback""", """callback_steps""", } __lowercase = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase = False def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) _snake_case = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) torch.manual_seed(0 ) _snake_case = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , latent_channels=4 , ) torch.manual_seed(0 ) _snake_case = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) _snake_case = CLIPTextModel(lowerCAmelCase_ ) _snake_case = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _snake_case = { 'unet': unet, 'scheduler': scheduler, 'vqvae': vae, 'bert': text_encoder, 'tokenizer': tokenizer, } return components def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ): """simple docstring""" if str(lowerCAmelCase_ ).startswith('mps' ): _snake_case = torch.manual_seed(lowerCAmelCase_ ) else: _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = LDMTextToImagePipeline(**lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase_ ) _snake_case = pipe(**lowerCAmelCase_ ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) _snake_case = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=torch.floataa , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.manual_seed(lowerCAmelCase_ ) _snake_case = np.random.RandomState(lowerCAmelCase_ ).standard_normal((1, 4, 32, 32) ) _snake_case = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) _snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256' ).to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_inputs(lowerCAmelCase_ ) _snake_case = pipe(**lowerCAmelCase_ ).images _snake_case = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 2_56, 2_56, 3) _snake_case = np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878] ) _snake_case = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=torch.floataa , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.manual_seed(lowerCAmelCase_ ) _snake_case = np.random.RandomState(lowerCAmelCase_ ).standard_normal((1, 4, 32, 32) ) _snake_case = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) _snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'latents': latents, 'generator': generator, 'num_inference_steps': 50, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256' ).to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = self.get_inputs(lowerCAmelCase_ ) _snake_case = pipe(**lowerCAmelCase_ ).images[0] _snake_case = load_numpy( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy' ) _snake_case = np.abs(expected_image - image ).max() assert max_diff < 1E-3
42
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class lowerCamelCase_ ( datasets.BeamBasedBuilder ): '''simple docstring''' def UpperCamelCase__ ( self) -> Union[str, Any]: return datasets.DatasetInfo( features=datasets.Features({'''content''': datasets.Value('''string''')}) , supervised_keys=__lowercase , ) def UpperCamelCase__ ( self , __lowercase , __lowercase) -> Optional[int]: return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_dummy_examples()})] def UpperCamelCase__ ( self , __lowercase , __lowercase) -> List[str]: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(__lowercase) class lowerCamelCase_ ( datasets.BeamBasedBuilder ): '''simple docstring''' def UpperCamelCase__ ( self) -> Dict: return datasets.DatasetInfo( features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''')})}) , supervised_keys=__lowercase , ) def UpperCamelCase__ ( self , __lowercase , __lowercase) -> Dict: return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_nested_examples()}) ] def UpperCamelCase__ ( self , __lowercase , __lowercase) -> Optional[int]: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(__lowercase) def lowerCamelCase ( ): '''simple docstring''' return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] def lowerCamelCase ( ): '''simple docstring''' return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' @require_beam def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Any = len(get_test_dummy_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: __UpperCamelCase :Optional[int] = DummyBeamDataset(cache_dir=__lowercase , beam_runner='''DirectRunner''') builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(__lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow"""))) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''')})) __UpperCamelCase :str = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , __lowercase) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __lowercase) self.assertDictEqual(dset['''train'''][0] , get_test_dummy_examples()[0][1]) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1]) self.assertTrue( os.path.exists(os.path.join(__lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json'''))) del dset @require_beam def UpperCamelCase__ ( self) -> Any: import apache_beam as beam __UpperCamelCase :int = beam.io.parquetio.WriteToParquet __UpperCamelCase :Optional[int] = len(get_test_dummy_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: __UpperCamelCase :Optional[int] = DummyBeamDataset(cache_dir=__lowercase , beam_runner='''DirectRunner''') with patch('''apache_beam.io.parquetio.WriteToParquet''') as write_parquet_mock: __UpperCamelCase :List[Any] = partial(__lowercase , num_shards=2) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( __lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow"""))) self.assertTrue( os.path.exists( os.path.join( __lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow"""))) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''')})) __UpperCamelCase :Dict = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , __lowercase) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __lowercase) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset['''train''']['''content''']) , sorted(['''foo''', '''bar''', '''foobar'''])) self.assertTrue( os.path.exists(os.path.join(__lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json'''))) del dset @require_beam def UpperCamelCase__ ( self) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_cache_dir: __UpperCamelCase :Optional[int] = DummyBeamDataset(cache_dir=__lowercase) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare) @require_beam def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Dict = len(get_test_nested_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: __UpperCamelCase :Tuple = NestedBeamDataset(cache_dir=__lowercase , beam_runner='''DirectRunner''') builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(__lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow"""))) self.assertDictEqual( builder.info.features , datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''')})})) __UpperCamelCase :Union[str, Any] = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , __lowercase) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __lowercase) self.assertDictEqual(dset['''train'''][0] , get_test_nested_examples()[0][1]) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1]) self.assertTrue( os.path.exists(os.path.join(__lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json'''))) del dset
43
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
"""simple docstring""" _a : Union[str, Any] = '0.21.0' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
44
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
"""simple docstring""" import logging import os from .state import PartialState class __lowerCAmelCase ( logging.LoggerAdapter ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __UpperCAmelCase ( self , _a , _a , *_a , **_a ): if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __a = kwargs.pop('''main_process_only''' , _a ) __a = kwargs.pop('''in_order''' , _a ) if self.isEnabledFor(_a ): if self._should_log(_a ): __a , __a = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) elif in_order: __a = PartialState() for i in range(state.num_processes ): if i == state.process_index: __a , __a = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) state.wait_for_everyone() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str = None ) -> Any: if log_level is None: __a = os.environ.get('''ACCELERATE_LOG_LEVEL''' , lowerCAmelCase__ ) __a = logging.getLogger(lowerCAmelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCAmelCase__ , {} )
45
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowercase : @staticmethod def _snake_case ( *lowercase , **lowercase ) -> Any: pass @is_pipeline_test @require_vision class lowercase ( unittest.TestCase ): @require_torch def _snake_case ( self ) -> List[str]: lowerCAmelCase = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , ) lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase = image_classifier(lowercase , candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(lowercase ) , [ [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}], [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}], ] , ) lowerCAmelCase = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowercase ) , [ [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], ] , ) @require_tf def _snake_case ( self ) -> List[str]: lowerCAmelCase = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""" ) lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase = image_classifier(lowercase , candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(lowercase ) , [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}] , ) lowerCAmelCase = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowercase ) , [ [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], [ {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, {"""score""": 0.333, """label""": ANY(lowercase )}, ], ] , ) @slow @require_torch def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , ) # This is an image of 2 cats with remotes and no planes lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase = image_classifier(lowercase , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(lowercase ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) lowerCAmelCase = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowercase ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , ) @slow @require_tf def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""" ) # This is an image of 2 cats with remotes and no planes lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase = image_classifier(lowercase , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(lowercase ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) lowerCAmelCase = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(lowercase ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , )
46
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
'''simple docstring''' import math import unittest from transformers import BioGptConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self : str , _a : List[Any] , _a : Optional[Any]=13 , _a : Tuple=7 , _a : int=True , _a : Tuple=True , _a : Any=False , _a : Tuple=True , _a : Optional[int]=99 , _a : List[Any]=32 , _a : Dict=5 , _a : List[str]=4 , _a : str=37 , _a : Dict="gelu" , _a : Optional[int]=0.1 , _a : int=0.1 , _a : List[Any]=512 , _a : int=16 , _a : List[str]=2 , _a : Union[str, Any]=0.02 , _a : Any=3 , _a : str=4 , _a : str=None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =seq_length _SCREAMING_SNAKE_CASE =is_training _SCREAMING_SNAKE_CASE =use_input_mask _SCREAMING_SNAKE_CASE =use_token_type_ids _SCREAMING_SNAKE_CASE =use_labels _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =type_sequence_label_size _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =num_choices _SCREAMING_SNAKE_CASE =scope def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE =None if self.use_input_mask: _SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self : Optional[int] ) -> Any: '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def A ( self : Tuple , _a : str , _a : str , _a : Optional[int] , _a : List[str] , _a : Dict , _a : Union[str, Any] , _a : int ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a ) _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : Union[str, Any] , _a : List[str] , _a : Optional[Any] , _a : str , _a : Optional[int] , _a : Optional[Any] , _a : Dict , _a : Optional[int] , _a : List[Any] , _a : str , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self : int , _a : Dict , _a : Tuple , _a : List[str] , _a : str , _a : Optional[int] , *_a : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ) model.to(_a ) model.eval() # create attention mask _SCREAMING_SNAKE_CASE =torch.ones(input_ids.shape , dtype=torch.long , device=_a ) _SCREAMING_SNAKE_CASE =self.seq_length // 2 _SCREAMING_SNAKE_CASE =0 # first forward pass _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a ).to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids _SCREAMING_SNAKE_CASE =ids_tensor((1,) , _a ).item() + 1 _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) _SCREAMING_SNAKE_CASE =random_other_next_tokens # append to next input_ids and attn_mask _SCREAMING_SNAKE_CASE =torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE =torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=_a )] , dim=1 , ) # get two different outputs _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a )['last_hidden_state'] _SCREAMING_SNAKE_CASE =model(_a , past_key_values=_a , attention_mask=_a )['last_hidden_state'] # select random slice _SCREAMING_SNAKE_CASE =ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE =output_from_no_past[:, -1, random_slice_idx].detach() _SCREAMING_SNAKE_CASE =output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1e-3 ) ) def A ( self : Any , _a : Dict , _a : List[Any] , _a : str , _a : List[str] , _a : Any , *_a : List[str] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ).to(_a ).eval() _SCREAMING_SNAKE_CASE =torch.ones(input_ids.shape , dtype=torch.long , device=_a ) # first forward pass _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , use_cache=_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and _SCREAMING_SNAKE_CASE =torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE =torch.cat([attention_mask, next_attn_mask] , dim=-1 ) _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a )['last_hidden_state'] _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , past_key_values=_a )[ 'last_hidden_state' ] # select random slice _SCREAMING_SNAKE_CASE =ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE =output_from_no_past[:, -3:, random_slice_idx].detach() _SCREAMING_SNAKE_CASE =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1e-3 ) ) def A ( self : Optional[int] , _a : Dict , _a : Any , _a : List[Any] , _a : Tuple , _a : Dict , *_a : Optional[Any] , _a : int=False ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM(_a ) model.to(_a ) if gradient_checkpointing: model.gradient_checkpointing_enable() _SCREAMING_SNAKE_CASE =model(_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def A ( self : int , _a : Dict , *_a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(_a ) _SCREAMING_SNAKE_CASE =model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_01 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def A ( self : Optional[int] , _a : Dict , _a : int , _a : Tuple , _a : Union[str, Any] , _a : Optional[int] , *_a : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =BioGptForTokenClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) =config_and_inputs _SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( A__ , A__ , A__ , unittest.TestCase ): A__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) A__ = (BioGptForCausalLM,) if is_torch_available() else () A__ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) A__ = False def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , hidden_size=37 ) def A ( self : str ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def A ( self : Optional[int] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def A ( self : Tuple ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _SCREAMING_SNAKE_CASE =type self.model_tester.create_and_check_model(*_a ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*_a , gradient_checkpointing=_a ) def A ( self : Any ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*_a ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*_a ) @slow def A ( self : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_a ) _SCREAMING_SNAKE_CASE =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE ='left' # Define PAD Token = EOS Token = 50256 _SCREAMING_SNAKE_CASE =tokenizer.eos_token _SCREAMING_SNAKE_CASE =model.config.eos_token_id # use different length sentences to test batching _SCREAMING_SNAKE_CASE =[ 'Hello, my dog is a little', 'Today, I', ] _SCREAMING_SNAKE_CASE =tokenizer(_a , return_tensors='pt' , padding=_a ) _SCREAMING_SNAKE_CASE =inputs['input_ids'].to(_a ) _SCREAMING_SNAKE_CASE =model.generate( input_ids=_a , attention_mask=inputs['attention_mask'].to(_a ) , ) _SCREAMING_SNAKE_CASE =tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(_a ) _SCREAMING_SNAKE_CASE =model.generate(input_ids=_a ) _SCREAMING_SNAKE_CASE =inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() _SCREAMING_SNAKE_CASE =tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(_a ) _SCREAMING_SNAKE_CASE =model.generate(input_ids=_a , max_length=model.config.max_length - num_paddings ) _SCREAMING_SNAKE_CASE =tokenizer.batch_decode(_a , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_non_padded[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_padded[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =[ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(_a , _a ) self.assertListEqual(_a , [non_padded_sentence, padded_sentence] ) @slow def A ( self : str ) -> Any: '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE =BioGptModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =input_dict['input_ids'] _SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(_a ) _SCREAMING_SNAKE_CASE =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =BioGptForSequenceClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def A ( self : Tuple ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE ='multi_label_classification' _SCREAMING_SNAKE_CASE =input_dict['input_ids'] _SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(_a ) _SCREAMING_SNAKE_CASE =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _SCREAMING_SNAKE_CASE =BioGptForSequenceClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class A__ ( unittest.TestCase ): @slow def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE =torch.tensor([[2, 4805, 9, 656, 21]] ) _SCREAMING_SNAKE_CASE =model(_a )[0] _SCREAMING_SNAKE_CASE =4_2384 _SCREAMING_SNAKE_CASE =torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , _a ) _SCREAMING_SNAKE_CASE =torch.tensor( [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1e-4 ) ) @slow def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_a ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =tokenizer('COVID-19 is' , return_tensors='pt' ).to(_a ) _SCREAMING_SNAKE_CASE =model.generate( **_a , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=_a , ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_ids[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(_a , _a )
47
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
48
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
import torch def __snake_case ( ): if torch.cuda.is_available(): __a = torch.cuda.device_count() else: __a = 0 print(f'Successfully ran on {num_gpus} GPUs' ) if __name__ == "__main__": main()
49
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
from __future__ import annotations from typing import Any class lowerCAmelCase : def __init__( self : Tuple , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : float = 0 ) -> None: lowerCamelCase__ , lowerCamelCase__ : str = row, column lowerCamelCase__ : str = [[default_value for c in range(UpperCAmelCase )] for r in range(UpperCAmelCase )] def __str__( self : str ) -> str: lowerCamelCase__ : str = F"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier lowerCamelCase__ : Optional[int] = 0 for row_vector in self.array: for obj in row_vector: lowerCamelCase__ : List[Any] = max(UpperCAmelCase , len(str(UpperCAmelCase ) ) ) lowerCamelCase__ : List[Any] = F"""%{max_element_length}s""" # Make string and return def single_line(UpperCAmelCase : list[float] ) -> str: nonlocal string_format_identifier lowerCamelCase__ : List[Any] = '[' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[Any] ) -> str: return str(self ) def A_ ( self : Any , UpperCAmelCase : tuple[int, int] ) -> bool: if not (isinstance(UpperCAmelCase , (list, tuple) ) and len(UpperCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(UpperCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : str , UpperCAmelCase : tuple[int, int] , UpperCAmelCase : float ) -> None: assert self.validate_indicies(UpperCAmelCase ) lowerCamelCase__ : Dict = value def __add__( self : Optional[Any] , UpperCAmelCase : Matrix ) -> Matrix: assert isinstance(UpperCAmelCase , UpperCAmelCase ) assert self.row == another.row and self.column == another.column # Add lowerCamelCase__ : List[Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowerCamelCase__ : Dict = self[r, c] + another[r, c] return result def __neg__( self : Dict ) -> Matrix: lowerCamelCase__ : int = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowerCamelCase__ : List[str] = -self[r, c] return result def __sub__( self : List[Any] , UpperCAmelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Tuple , UpperCAmelCase : int | float | Matrix ) -> Matrix: if isinstance(UpperCAmelCase , (int, float) ): # Scalar multiplication lowerCamelCase__ : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): lowerCamelCase__ : Dict = self[r, c] * another return result elif isinstance(UpperCAmelCase , UpperCAmelCase ): # Matrix multiplication assert self.column == another.row lowerCamelCase__ : Optional[int] = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: lowerCamelCase__ : Any = F"""Unsupported type given for another ({type(UpperCAmelCase )})""" raise TypeError(UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Matrix: lowerCamelCase__ : str = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): lowerCamelCase__ : Tuple = self[r, c] return result def A_ ( self : Tuple , UpperCAmelCase : Matrix , UpperCAmelCase : Matrix ) -> Any: assert isinstance(UpperCAmelCase , UpperCAmelCase ) and isinstance(UpperCAmelCase , UpperCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate lowerCamelCase__ : Any = v.transpose() lowerCamelCase__ : Dict = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( ) -> None: # a^(-1) lowerCamelCase__ : str = Matrix(3 , 3 , 0 ) for i in range(3 ): lowerCamelCase__ : str = 1 print(F"""a^(-1) is {ainv}""" ) # u, v lowerCamelCase__ : Any = Matrix(3 , 1 , 0 ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Tuple = 1, 2, -3 lowerCamelCase__ : Tuple = Matrix(3 , 1 , 0 ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = 4, -2, 5 print(F"""u is {u}""" ) print(F"""v is {v}""" ) print(F"""uv^T is {u * v.transpose()}""" ) # Sherman Morrison print(F"""(a + uv^T)^(-1) is {ainv.sherman_morrison(_UpperCAmelCase , _UpperCAmelCase )}""" ) def SCREAMING_SNAKE_CASE ( ) -> None: import doctest doctest.testmod() testa()
50
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class __snake_case : def __init__( self : List[str] , _snake_case : Union[str, Any] , _snake_case : List[str]=2 , _snake_case : Any=True , _snake_case : Any=False , _snake_case : List[str]=10 , _snake_case : Any=3 , _snake_case : Union[str, Any]=32 * 4 , _snake_case : List[Any]=32 * 6 , _snake_case : Tuple=4 , _snake_case : Dict=32 , ): """simple docstring""" UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = is_training UpperCAmelCase_ = use_auxiliary_loss UpperCAmelCase_ = num_queries UpperCAmelCase_ = num_channels UpperCAmelCase_ = min_size UpperCAmelCase_ = max_size UpperCAmelCase_ = num_labels UpperCAmelCase_ = mask_feature_size def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( _snake_case) UpperCAmelCase_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_snake_case) UpperCAmelCase_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_snake_case) > 0.5 ).float() UpperCAmelCase_ = (torch.rand((self.batch_size, self.num_labels) , device=_snake_case) > 0.5).long() UpperCAmelCase_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCamelCase ( self : Any): """simple docstring""" return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def lowerCamelCase ( self : int): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def lowerCamelCase ( self : str , _snake_case : List[Any] , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = output.encoder_hidden_states UpperCAmelCase_ = output.pixel_decoder_hidden_states UpperCAmelCase_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_snake_case) , len(config.backbone_config.depths)) self.parent.assertTrue(len(_snake_case) , len(config.backbone_config.depths)) self.parent.assertTrue(len(_snake_case) , config.decoder_config.decoder_layers) def lowerCamelCase ( self : Union[str, Any] , _snake_case : List[str] , _snake_case : int , _snake_case : Optional[Any] , _snake_case : str=False): """simple docstring""" with torch.no_grad(): UpperCAmelCase_ = MaskFormerModel(config=_snake_case) model.to(_snake_case) model.eval() UpperCAmelCase_ = model(pixel_values=_snake_case , pixel_mask=_snake_case) UpperCAmelCase_ = model(_snake_case , output_hidden_states=_snake_case) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(_snake_case , _snake_case) def lowerCamelCase ( self : List[Any] , _snake_case : List[Any] , _snake_case : List[Any] , _snake_case : str , _snake_case : Optional[int] , _snake_case : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerForInstanceSegmentation(config=_snake_case) model.to(_snake_case) model.eval() def comm_check_on_output(_snake_case : Tuple): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): UpperCAmelCase_ = model(pixel_values=_snake_case , pixel_mask=_snake_case) UpperCAmelCase_ = model(_snake_case) comm_check_on_output(_snake_case) UpperCAmelCase_ = model( pixel_values=_snake_case , pixel_mask=_snake_case , mask_labels=_snake_case , class_labels=_snake_case) comm_check_on_output(_snake_case) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class __snake_case ( a , a , unittest.TestCase ): UpperCAmelCase__ : Union[str, Any] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () UpperCAmelCase__ : Optional[Any] = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) UpperCAmelCase__ : Dict = False UpperCAmelCase__ : List[str] = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Union[str, Any] = False def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerModelTester(self) UpperCAmelCase_ = ConfigTester(self , config_class=_snake_case , has_text_modality=_snake_case) def lowerCamelCase ( self : List[Any]): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_snake_case , **_snake_case , output_hidden_states=_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_snake_case) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''') def lowerCamelCase ( self : Dict): """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''') def lowerCamelCase ( self : int): """simple docstring""" pass @unittest.skip(reason='''MaskFormer is not a generative model''') def lowerCamelCase ( self : str): """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not use token embeddings''') def lowerCamelCase ( self : int): """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''') def lowerCamelCase ( self : Any): """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def lowerCamelCase ( self : str): """simple docstring""" pass def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(_snake_case) UpperCAmelCase_ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _snake_case) @slow def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCAmelCase_ = MaskFormerModel.from_pretrained(_snake_case) self.assertIsNotNone(_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = (self.model_tester.min_size,) * 2 UpperCAmelCase_ = { '''pixel_values''': torch.randn((2, 3, *size) , device=_snake_case), '''mask_labels''': torch.randn((2, 10, *size) , device=_snake_case), '''class_labels''': torch.zeros(2 , 10 , device=_snake_case).long(), } UpperCAmelCase_ = MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(_snake_case) UpperCAmelCase_ = model(**_snake_case) self.assertTrue(outputs.loss is not None) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_snake_case , **_snake_case , output_hidden_states=_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(_snake_case).to(_snake_case) UpperCAmelCase_ = model(**_snake_case , output_attentions=_snake_case) self.assertTrue(outputs.attentions is not None) def lowerCamelCase ( self : int): """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = model_class(_snake_case) model.to(_snake_case) model.train() UpperCAmelCase_ = model(_snake_case , mask_labels=_snake_case , class_labels=_snake_case).loss loss.backward() def lowerCamelCase ( self : Optional[int]): """simple docstring""" UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = True UpperCAmelCase_ = True UpperCAmelCase_ = model_class(_snake_case) model.to(_snake_case) model.train() UpperCAmelCase_ = model(_snake_case , mask_labels=_snake_case , class_labels=_snake_case) UpperCAmelCase_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't UpperCAmelCase_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_snake_case) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) snake_case_ : Dict = 1e-4 def A () -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class __snake_case ( unittest.TestCase ): @cached_property def lowerCamelCase ( self : List[str]): """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''') if is_vision_available() else None ) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''').to(_snake_case) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) UpperCAmelCase_ = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _snake_case , atol=_snake_case)) UpperCAmelCase_ = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _snake_case , atol=_snake_case)) UpperCAmelCase_ = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) # masks_queries_logits UpperCAmelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCAmelCase_ = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] UpperCAmelCase_ = torch.tensor(_snake_case).to(_snake_case) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _snake_case , atol=_snake_case)) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)) UpperCAmelCase_ = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ]).to(_snake_case) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) # masks_queries_logits UpperCAmelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCAmelCase_ = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] UpperCAmelCase_ = torch.tensor(_snake_case).to(_snake_case) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _snake_case , atol=_snake_case)) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)) UpperCAmelCase_ = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]]).to(_snake_case) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors='''pt''' , ) UpperCAmelCase_ = inputs['''pixel_values'''].to(_snake_case) UpperCAmelCase_ = [el.to(_snake_case) for el in inputs['''mask_labels''']] UpperCAmelCase_ = [el.to(_snake_case) for el in inputs['''class_labels''']] with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) self.assertTrue(outputs.loss is not None)
51
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class A__ ( unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=3 , A_=30 , A_=400 , A_=True , A_=None , A_=True , A_=[0.5, 0.5, 0.5] , A_=[0.5, 0.5, 0.5] , A_=True , A_=1 / 255 , A_=True , ): '''simple docstring''' UpperCamelCase : Dict = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} UpperCamelCase : List[str] = parent UpperCamelCase : Dict = batch_size UpperCamelCase : str = num_channels UpperCamelCase : Optional[Any] = min_resolution UpperCamelCase : Dict = max_resolution UpperCamelCase : int = do_resize UpperCamelCase : Any = size UpperCamelCase : Tuple = do_normalize UpperCamelCase : Optional[int] = image_mean UpperCamelCase : Union[str, Any] = image_std UpperCamelCase : Optional[int] = do_rescale UpperCamelCase : str = rescale_factor UpperCamelCase : int = do_pad def __UpperCamelCase( self ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __UpperCamelCase( self , A_ , A_=False ): '''simple docstring''' if not batched: UpperCamelCase : Optional[int] = image_inputs[0] if isinstance(A_ , Image.Image ): UpperCamelCase , UpperCamelCase : List[str] = image.size else: UpperCamelCase , UpperCamelCase : Tuple = image.shape[1], image.shape[2] if w < h: UpperCamelCase : Dict = int(self.size["shortest_edge"] * h / w ) UpperCamelCase : Dict = self.size["shortest_edge"] elif w > h: UpperCamelCase : Optional[int] = self.size["shortest_edge"] UpperCamelCase : Union[str, Any] = int(self.size["shortest_edge"] * w / h ) else: UpperCamelCase : List[str] = self.size["shortest_edge"] UpperCamelCase : Optional[int] = self.size["shortest_edge"] else: UpperCamelCase : List[Any] = [] for image in image_inputs: UpperCamelCase , UpperCamelCase : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase : List[Any] = max(A_ , key=lambda A_ : item[0] )[0] UpperCamelCase : int = max(A_ , key=lambda A_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :int = DeformableDetrImageProcessor if is_vision_available() else None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = DeformableDetrImageProcessingTester(self ) @property def __UpperCamelCase( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ , "image_mean" ) ) self.assertTrue(hasattr(A_ , "image_std" ) ) self.assertTrue(hasattr(A_ , "do_normalize" ) ) self.assertTrue(hasattr(A_ , "do_resize" ) ) self.assertTrue(hasattr(A_ , "do_rescale" ) ) self.assertTrue(hasattr(A_ , "do_pad" ) ) self.assertTrue(hasattr(A_ , "size" ) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , A_ ) UpperCamelCase : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A_ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , A_ ) def __UpperCamelCase( self ): '''simple docstring''' pass def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ ) for image in image_inputs: self.assertIsInstance(A_ , Image.Image ) # Test not batched input UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCamelCase , UpperCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase , UpperCamelCase : int = self.image_processor_tester.get_expected_values(A_ , batched=A_ ) UpperCamelCase : Any = image_processing(A_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , numpify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , np.ndarray ) # Test not batched input UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCamelCase , UpperCamelCase : int = self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase : Optional[int] = image_processing(A_ , return_tensors="pt" ).pixel_values UpperCamelCase , UpperCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , torchify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , torch.Tensor ) # Test not batched input UpperCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCamelCase , UpperCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase : Union[str, Any] = image_processing(A_ , return_tensors="pt" ).pixel_values UpperCamelCase , UpperCamelCase : Dict = self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: UpperCamelCase : str = json.loads(f.read() ) UpperCamelCase : Dict = {"image_id": 3_9769, "annotations": target} # encode them UpperCamelCase : str = DeformableDetrImageProcessor() UpperCamelCase : Optional[Any] = image_processing(images=A_ , annotations=A_ , return_tensors="pt" ) # verify pixel values UpperCamelCase : Optional[int] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , A_ ) UpperCamelCase : Any = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A_ , atol=1e-4 ) ) # verify area UpperCamelCase : Union[str, Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A_ ) ) # verify boxes UpperCamelCase : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A_ ) UpperCamelCase : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A_ , atol=1e-3 ) ) # verify image_id UpperCamelCase : Optional[Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A_ ) ) # verify is_crowd UpperCamelCase : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A_ ) ) # verify class_labels UpperCamelCase : str = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A_ ) ) # verify orig_size UpperCamelCase : Dict = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A_ ) ) # verify size UpperCamelCase : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A_ ) ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: UpperCamelCase : Optional[int] = json.loads(f.read() ) UpperCamelCase : Any = {"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target} UpperCamelCase : Tuple = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them UpperCamelCase : List[Any] = DeformableDetrImageProcessor(format="coco_panoptic" ) UpperCamelCase : Dict = image_processing(images=A_ , annotations=A_ , masks_path=A_ , return_tensors="pt" ) # verify pixel values UpperCamelCase : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , A_ ) UpperCamelCase : List[Any] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , A_ , atol=1e-4 ) ) # verify area UpperCamelCase : Union[str, Any] = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , A_ ) ) # verify boxes UpperCamelCase : Dict = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , A_ ) UpperCamelCase : Any = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , A_ , atol=1e-3 ) ) # verify image_id UpperCamelCase : Union[str, Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , A_ ) ) # verify is_crowd UpperCamelCase : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , A_ ) ) # verify class_labels UpperCamelCase : Any = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , A_ ) ) # verify masks UpperCamelCase : Dict = 82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , A_ ) # verify orig_size UpperCamelCase : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , A_ ) ) # verify size UpperCamelCase : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , A_ ) )
52
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a__ : int =logging.get_logger(__name__) a__ : Any ={'''vocab_file''': '''sentencepiece.bpe.model'''} a__ : List[str] ={ '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', } } a__ : int ={ '''camembert-base''': 512, } a__ : List[Any] ='''▁''' class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] =VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ : int =PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ : int =["input_ids", "attention_mask"] def __init__( self : List[Any] , __A : Tuple , __A : int="<s>" , __A : Dict="</s>" , __A : str="</s>" , __A : str="<s>" , __A : Dict="<unk>" , __A : List[str]="<pad>" , __A : Dict="<mask>" , __A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , __A : Optional[Dict[str, Any]] = None , **__A : Optional[int] , ): # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token __UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , additional_special_tokens=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) __UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) __UpperCamelCase = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __UpperCamelCase = {'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3} __UpperCamelCase = len(self.fairseq_tokens_to_ids ) __UpperCamelCase = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def _lowerCamelCase ( self : Any , __A : List[int] , __A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase = [self.cls_token_id] __UpperCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowerCamelCase ( self : List[str] , __A : List[int] , __A : Optional[List[int]] = None , __A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def _lowerCamelCase ( self : Tuple , __A : List[int] , __A : Optional[List[int]] = None ): __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _lowerCamelCase ( self : Any ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def _lowerCamelCase ( self : List[str] ): __UpperCamelCase = {self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowerCamelCase ( self : Union[str, Any] , __A : str ): return self.sp_model.encode(__A , out_type=__A ) def _lowerCamelCase ( self : str , __A : List[str] ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(__A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(__A ) def _lowerCamelCase ( self : Any , __A : Union[str, Any] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _lowerCamelCase ( self : Tuple , __A : List[str] ): __UpperCamelCase = [] __UpperCamelCase = '' __UpperCamelCase = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token __UpperCamelCase = True __UpperCamelCase = [] else: current_sub_tokens.append(__A ) __UpperCamelCase = False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self : Optional[int] ): __UpperCamelCase = self.__dict__.copy() __UpperCamelCase = None return state def __setstate__( self : Tuple , __A : Tuple ): __UpperCamelCase = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase = {} __UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self : int , __A : str , __A : Optional[str] = None ): if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCamelCase = os.path.join( __A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , 'wb' ) as fi: __UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
53
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
"""simple docstring""" a__ : int = '''Tobias Carryer''' from time import time class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=int(time() ) ) -> int: # noqa: B008 __SCREAMING_SNAKE_CASE = multiplier __SCREAMING_SNAKE_CASE = increment __SCREAMING_SNAKE_CASE = modulo __SCREAMING_SNAKE_CASE = seed def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. a__ : Optional[int] = LinearCongruentialGenerator(1_6_6_4_5_2_5, 1_0_1_3_9_0_4_2_2_3, 2 << 3_1) while True: print(lcg.next_number())
54
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
'''simple docstring''' def __snake_case ( UpperCAmelCase_ : int = 1000 ): lowerCamelCase_ = 2**power lowerCamelCase_ = 0 while n: lowerCamelCase_ ,lowerCamelCase_ = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
55
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> List[Any]: '''simple docstring''' if isinstance(__UpperCAmelCase, __UpperCAmelCase ): snake_case_ = np.full((len(__UpperCAmelCase ), sequence_length, 2), __UpperCAmelCase ) else: snake_case_ = np.full((len(__UpperCAmelCase ), sequence_length), __UpperCAmelCase ) for i, tensor in enumerate(__UpperCAmelCase ): if padding_side == "right": if isinstance(__UpperCAmelCase, __UpperCAmelCase ): snake_case_ = tensor[:sequence_length] else: snake_case_ = tensor[:sequence_length] else: if isinstance(__UpperCAmelCase, __UpperCAmelCase ): snake_case_ = tensor[:sequence_length] else: snake_case_ = tensor[:sequence_length] return out_tensor.tolist() def __magic_name__ ( __UpperCAmelCase ) -> Dict: '''simple docstring''' snake_case_ = ord(__UpperCAmelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True snake_case_ = unicodedata.category(__UpperCAmelCase ) if cat.startswith('''P''' ): return True return False @dataclass class a ( _lowerCamelCase ): snake_case_ = 42 snake_case_ = True snake_case_ = None snake_case_ = None snake_case_ = -100 snake_case_ = "pt" def A_ ( self : int , lowercase_ : List[str] ): import torch snake_case_ = '''label''' if '''label''' in features[0].keys() else '''labels''' snake_case_ = [feature[label_name] for feature in features] if label_name in features[0].keys() else None snake_case_ = self.tokenizer.pad( lowercase_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch snake_case_ = torch.tensor(batch['''entity_ids'''] ).shape[1] snake_case_ = self.tokenizer.padding_side if padding_side == "right": snake_case_ = [ list(lowercase_ ) + [self.label_pad_token_id] * (sequence_length - len(lowercase_ )) for label in labels ] else: snake_case_ = [ [self.label_pad_token_id] * (sequence_length - len(lowercase_ )) + list(lowercase_ ) for label in labels ] snake_case_ = [feature['''ner_tags'''] for feature in features] snake_case_ = padding_tensor(lowercase_ , -1 , lowercase_ , lowercase_ ) snake_case_ = [feature['''original_entity_spans'''] for feature in features] snake_case_ = padding_tensor(lowercase_ , (-1, -1) , lowercase_ , lowercase_ ) snake_case_ = {k: torch.tensor(lowercase_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
56
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
"""simple docstring""" import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json A : Optional[int] = "sshleifer/mar_enro_6_3_student" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def snake_case ( self ): super().setUp() __lowerCAmelCase = cached_path( "https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz" , extract_compressed_file=__a , ) __lowerCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def snake_case ( self ): MarianMTModel.from_pretrained(__a ) @slow @require_torch_gpu def snake_case ( self ): __lowerCAmelCase = { "$MAX_LEN": 64, "$BS": 64, "$GAS": 1, "$ENRO_DIR": self.data_dir, "facebook/mbart-large-cc25": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", "--learning_rate=3e-5": "--learning_rate 3e-4", "--num_train_epochs 6": "--num_train_epochs 1", } # Clean up bash script __lowerCAmelCase = (self.test_file_dir / "train_mbart_cc25_enro.sh").open().read().split("finetune.py" )[1].strip() __lowerCAmelCase = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) for k, v in env_vars_to_replace.items(): __lowerCAmelCase = bash_script.replace(__a , str(__a ) ) __lowerCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") __lowerCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future __lowerCAmelCase = ["finetune.py"] + bash_script.split() + args with patch.object(__a , "argv" , __a ): __lowerCAmelCase = argparse.ArgumentParser() __lowerCAmelCase = pl.Trainer.add_argparse_args(__a ) __lowerCAmelCase = SummarizationModule.add_model_specific_args(__a , os.getcwd() ) __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = main(__a ) # Check metrics __lowerCAmelCase = load_json(model.metrics_save_path ) __lowerCAmelCase = metrics["val"][0] __lowerCAmelCase = metrics["val"][-1] self.assertEqual(len(metrics["val"] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , __a ) self.assertGreater(last_step_stats["val_avg_gen_time"] , 0.0_1 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["val_avg_gen_time"] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["val_avg_bleu"] - first_step_stats["val_avg_bleu"] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["val_avg_bleu"] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["val"][-1]["val_avg_bleu"] - metrics["test"][-1]["test_avg_bleu"] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict __lowerCAmelCase = os.listdir(__a ) __lowerCAmelCase = [x for x in contents if x.endswith(".ckpt" )][0] __lowerCAmelCase = os.path.join(args.output_dir , __a ) __lowerCAmelCase = torch.load(__a , map_location="cpu" ) __lowerCAmelCase = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __lowerCAmelCase = {os.path.basename(__a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1 class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' @timeout_decorator.timeout(6_00 ) @slow @require_torch_gpu def snake_case ( self ): __lowerCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" __lowerCAmelCase = { "--fp16_opt_level=O1": "", "$MAX_LEN": 1_28, "$BS": 16, "$GAS": 1, "$ENRO_DIR": data_dir, "$m": "sshleifer/student_marian_en_ro_6_1", "val_check_interval=0.25": "val_check_interval=1.0", } # Clean up bash script __lowerCAmelCase = ( (self.test_file_dir / "distil_marian_no_teacher.sh").open().read().split("distillation.py" )[1].strip() ) __lowerCAmelCase = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) __lowerCAmelCase = bash_script.replace("--fp16 " , " " ) for k, v in env_vars_to_replace.items(): __lowerCAmelCase = bash_script.replace(__a , str(__a ) ) __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = bash_script.replace("--fp16" , "" ) __lowerCAmelCase = 6 __lowerCAmelCase = ( ["distillation.py"] + bash_script.split() + [ f"--output_dir={output_dir}", "--gpus=1", "--learning_rate=1e-3", f"--num_train_epochs={epochs}", "--warmup_steps=10", "--val_check_interval=1.0", "--do_predict", ] ) with patch.object(__a , "argv" , __a ): __lowerCAmelCase = argparse.ArgumentParser() __lowerCAmelCase = pl.Trainer.add_argparse_args(__a ) __lowerCAmelCase = SummarizationDistiller.add_model_specific_args(__a , os.getcwd() ) __lowerCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu __lowerCAmelCase = distill_main(__a ) # Check metrics __lowerCAmelCase = load_json(model.metrics_save_path ) __lowerCAmelCase = metrics["val"][0] __lowerCAmelCase = metrics["val"][-1] assert len(metrics["val"] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.0_1 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , __a ) # check lightning ckpt can be loaded and has a reasonable statedict __lowerCAmelCase = os.listdir(__a ) __lowerCAmelCase = [x for x in contents if x.endswith(".ckpt" )][0] __lowerCAmelCase = os.path.join(args.output_dir , __a ) __lowerCAmelCase = torch.load(__a , map_location="cpu" ) __lowerCAmelCase = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __lowerCAmelCase = {os.path.basename(__a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1
57
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->int: if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __lowerCamelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ __lowerCamelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ __lowerCamelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> MetricInfo: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _SCREAMING_SNAKE_CASE (self : int , snake_case__ : List[List[List[str]]] , snake_case__ : List[List[str]] , snake_case__ : int = 1 , snake_case__ : int = 4 , ) -> Dict[str, float]: '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=snake_case__ , hypotheses=snake_case__ , min_len=snake_case__ , max_len=snake_case__ ) }
59
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal snake_case__ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) snake_case__ : Optional[int] = ['''names''', '''prefix'''] snake_case__ : Any = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] snake_case__ : Any = ['''encoding_errors''', '''on_bad_lines'''] snake_case__ : Tuple = ['''date_format'''] @dataclass class snake_case_( datasets.BuilderConfig ): __UpperCamelCase = "," __UpperCamelCase = None __UpperCamelCase = "infer" __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = True __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = None __UpperCamelCase = "." __UpperCamelCase = None __UpperCamelCase = '"' __UpperCamelCase = 0 __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = 0 __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = None __UpperCamelCase = 10_000 __UpperCamelCase = None __UpperCamelCase = "strict" __UpperCamelCase = "error" __UpperCamelCase = None def lowerCamelCase__ ( self : Union[str, Any] ): if self.delimiter is not None: lowerCAmelCase : Dict = self.delimiter if self.column_names is not None: lowerCAmelCase : Dict = self.column_names @property def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Any = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , UpperCamelCase_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class snake_case_( datasets.ArrowBasedBuilder ): __UpperCamelCase = CsvConfig def lowerCamelCase__ ( self : List[str] ): return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : List[str] ): if not self.config.data_files: raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) lowerCAmelCase : Union[str, Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCamelCase_ , (str, list, tuple) ): lowerCAmelCase : Dict = data_files if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase : Tuple = [files] lowerCAmelCase : List[Any] = [dl_manager.iter_files(UpperCamelCase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] lowerCAmelCase : Tuple = [] for split_name, files in data_files.items(): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase : Optional[int] = [files] lowerCAmelCase : Dict = [dl_manager.iter_files(UpperCamelCase_ ) for file in files] splits.append(datasets.SplitGenerator(name=UpperCamelCase_ , gen_kwargs={'''files''': files} ) ) return splits def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : pa.Table ): if self.config.features is not None: lowerCAmelCase : Any = self.config.features.arrow_schema if all(not require_storage_cast(UpperCamelCase_ ) for feature in self.config.features.values() ): # cheaper cast lowerCAmelCase : Union[str, Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=UpperCamelCase_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example lowerCAmelCase : Any = table_cast(UpperCamelCase_ , UpperCamelCase_ ) return pa_table def lowerCamelCase__ ( self : Any , UpperCamelCase_ : str ): lowerCAmelCase : Tuple = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str lowerCAmelCase : Dict = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(UpperCamelCase_ ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCamelCase_ ) ): lowerCAmelCase : List[Any] = pd.read_csv(UpperCamelCase_ , iterator=UpperCamelCase_ , dtype=UpperCamelCase_ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(UpperCamelCase_ ): lowerCAmelCase : List[Any] = pa.Table.from_pandas(UpperCamelCase_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(UpperCamelCase_ ) except ValueError as e: logger.error(F'''Failed to read file \'{file}\' with error {type(UpperCamelCase_ )}: {e}''' ) raise
60
'''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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
"""simple docstring""" from typing import List import numpy as np def __a ( __lowerCamelCase ): UpperCAmelCase_ : Dict = {key: len(__lowerCamelCase ) for key, value in gen_kwargs.items() if isinstance(__lowerCamelCase, __lowerCamelCase )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( "Sharding is ambiguous for this dataset: " + "we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n" + "\n".join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() ) + "\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, " + "and use tuples otherwise. In the end there should only be one single list, or several lists with the same length." ) ) UpperCAmelCase_ : List[str] = max(lists_lengths.values(), default=0 ) return max(1, __lowerCamelCase ) def __a ( __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : Optional[int] = [] for group_idx in range(__lowerCamelCase ): UpperCAmelCase_ : Union[str, Any] = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break UpperCAmelCase_ : Optional[Any] = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 UpperCAmelCase_ : List[Any] = range(__lowerCamelCase, start + num_shards_to_add ) shards_indices_per_group.append(__lowerCamelCase ) return shards_indices_per_group def __a ( __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : Any = _number_of_shards_in_gen_kwargs(__lowerCamelCase ) if num_shards == 1: return [dict(__lowerCamelCase )] else: UpperCAmelCase_ : Any = _distribute_shards(num_shards=__lowerCamelCase, max_num_jobs=__lowerCamelCase ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(__lowerCamelCase, __lowerCamelCase ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(__lowerCamelCase ) ) ] def __a ( __lowerCamelCase ): return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key], __lowerCamelCase ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def __a ( __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : Union[str, Any] = {len(__lowerCamelCase ) for value in gen_kwargs.values() if isinstance(__lowerCamelCase, __lowerCamelCase )} UpperCAmelCase_ : List[str] = {} for size in list_sizes: UpperCAmelCase_ : Tuple = list(range(__lowerCamelCase ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes UpperCAmelCase_ : Optional[int] = dict(__lowerCamelCase ) for key, value in shuffled_kwargs.items(): if isinstance(__lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : str = [value[i] for i in indices_per_size[len(__lowerCamelCase )]] return shuffled_kwargs
61
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[int]: __UpperCamelCase =inspect.getfile(accelerate.test_utils ) __UpperCamelCase =os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __UpperCamelCase =test_metrics @require_cpu def _a ( self ) -> Optional[int]: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ) -> str: debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ) -> Optional[int]: self.test_metrics.main() @require_multi_gpu def _a ( self ) -> int: print(f'Found {torch.cuda.device_count()} devices.' ) __UpperCamelCase =['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A_ , env=os.environ.copy() )
62
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, 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 UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ : str = logging.get_logger(__name__) def _lowerCamelCase ( lowercase : int , lowercase : Union[str, Any]=False ) -> Optional[Any]: _a = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _a = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Tuple , lowercase : List[str]=False ) -> List[Any]: for i in range(config.num_hidden_layers ): if base_model: _a = "" else: _a = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _a = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) _a = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict _a = in_proj_weight[ : config.hidden_size, : ] _a = in_proj_bias[: config.hidden_size] _a = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _a = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _a = in_proj_weight[ -config.hidden_size :, : ] _a = in_proj_bias[-config.hidden_size :] def _lowerCamelCase ( lowercase : str ) -> List[str]: _a = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(lowercase , lowercase ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] , lowercase : Union[str, Any] ) -> int: _a = dct.pop(lowercase ) _a = val def _lowerCamelCase ( ) -> Dict: _a = "http://images.cocodataset.org/val2017/000000039769.jpg" _a = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : List[str] , lowercase : List[Any]=False ) -> List[str]: _a = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=lowercase , ) _a = ViTHybridConfig(backbone_config=lowercase , image_size=384 , num_labels=1000 ) _a = False # load original model from timm _a = timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() # load state_dict of original model, remove and rename some keys _a = timm_model.state_dict() if base_model: remove_classification_head_(lowercase ) _a = create_rename_keys(lowercase , lowercase ) for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) read_in_q_k_v(lowercase , lowercase , lowercase ) _a = "huggingface/label-files" _a = "imagenet-1k-id2label.json" _a = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) _a = {int(lowercase ): v for k, v in idalabel.items()} _a = idalabel _a = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": _a = ViTHybridModel(lowercase ).eval() else: _a = ViTHybridForImageClassification(lowercase ).eval() model.load_state_dict(lowercase ) # create image processor _a = create_transform(**resolve_data_config({} , model=lowercase ) ) _a = transform.transforms _a = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } _a = ViTHybridImageProcessor( do_resize=lowercase , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowercase , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) _a = prepare_img() _a = transform(lowercase ).unsqueeze(0 ) _a = processor(lowercase , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(lowercase , lowercase ) # verify logits with torch.no_grad(): _a = model(lowercase ) _a = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: _a = timm_model.forward_features(lowercase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowercase , outputs.pooler_output , atol=1E-3 ) else: _a = timm_model(lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'Saving model {vit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowercase ) print(F'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(lowercase ) if push_to_hub: print(F'Pushing model and processor to the hub {vit_name}' ) model.push_to_hub(F'ybelkada/{vit_name}' ) processor.push_to_hub(F'ybelkada/{vit_name}' ) if __name__ == "__main__": lowerCAmelCase_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) lowerCAmelCase_ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
63
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : str ): """simple docstring""" _snake_case : Optional[Any] = [] for part_id in partition_order: _snake_case : str = df.where(F"SPARK_PARTITION_ID() = {part_id}" ).collect() for row_idx, row in enumerate(snake_case__ ): expected_row_ids_and_row_dicts.append((F"{part_id}_{row_idx}", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : Optional[Any] = spark.range(1_00 ).repartition(1 ) _snake_case : Tuple = Spark(snake_case__ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : Tuple = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : int = spark.range(10 ).repartition(2 ) _snake_case : Tuple = [1, 0] _snake_case : Dict = _generate_iterable_examples(snake_case__ , snake_case__ ) # Reverse the partitions. _snake_case : Optional[int] = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , snake_case__ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): _snake_case , _snake_case : Optional[Any] = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : Any = spark.range(10 ).repartition(1 ) _snake_case : List[str] = SparkExamplesIterable(snake_case__ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(snake_case__ ): assert row_id == F"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : Tuple = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : int = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("""numpy.random.Generator""" ) as generator_mock: _snake_case : Tuple = lambda snake_case__ : x.reverse() _snake_case : List[str] = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [2, 1, 0] ) _snake_case : int = SparkExamplesIterable(snake_case__ ).shuffle_data_sources(snake_case__ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(snake_case__ ): _snake_case , _snake_case : List[Any] = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : int = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : Dict = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 _snake_case : List[Any] = SparkExamplesIterable(snake_case__ ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 _snake_case : Any = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [0, 2] ) for i, (row_id, row_dict) in enumerate(snake_case__ ): _snake_case , _snake_case : List[str] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 _snake_case : List[str] = SparkExamplesIterable(snake_case__ ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 _snake_case : Union[str, Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [1, 3] ) for i, (row_id, row_dict) in enumerate(snake_case__ ): _snake_case , _snake_case : Any = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _snake_case : Dict = spark.range(1_00 ).repartition(1 ) _snake_case : List[Any] = Spark(snake_case__ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
64
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowerCAmelCase_ ( __A, __A, __A=1_024, __A=1_024, __A=False, **__A ) -> int: '''simple docstring''' UpperCAmelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCAmelCase__ = SeqaSeqDataset(__A, __A, __A, __A, type_path="train", **__A ) UpperCAmelCase__ = tok.pad_token_id def get_lens(__A ): UpperCAmelCase__ = tqdm( DataLoader(__A, batch_size=512, num_workers=8, shuffle=__A, collate_fn=ds.collate_fn ), desc=str(ds.len_file ), ) UpperCAmelCase__ = [] for batch in dl: UpperCAmelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCAmelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A, __A ): max_lens.append(max(__A, __A ) ) else: max_lens.extend(__A ) return max_lens UpperCAmelCase__ = get_lens(__A ) UpperCAmelCase__ = SeqaSeqDataset(__A, __A, __A, __A, type_path="val", **__A ) UpperCAmelCase__ = get_lens(__A ) pickle_save(__A, train_ds.len_file ) pickle_save(__A, val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
65
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
"""simple docstring""" from math import isclose, sqrt def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' snake_case_ :List[Any] = point_y / 4 / point_x snake_case_ :Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) snake_case_ :Tuple = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) snake_case_ :str = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 snake_case_ :Tuple = outgoing_gradient**2 + 4 snake_case_ :List[str] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) snake_case_ :Dict = (point_y - outgoing_gradient * point_x) ** 2 - 100 snake_case_ :Optional[Any] = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) snake_case_ :List[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point snake_case_ :Dict = x_minus if isclose(_lowercase, _lowercase ) else x_plus snake_case_ :Optional[Any] = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def A_ ( _lowercase = 1.4, _lowercase = -9.6 ): '''simple docstring''' snake_case_ :int = 0 snake_case_ :float = first_x_coord snake_case_ :float = first_y_coord snake_case_ :float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): snake_case_, snake_case_, snake_case_ :List[Any] = next_point(_lowercase, _lowercase, _lowercase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
66
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
'''simple docstring''' def __lowerCAmelCase ( ) -> int: return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(UpperCamelCase__ , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'{solution() = }')
67
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = JukeboxTokenizer __lowerCamelCase = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics" ) A__ = tokenizer(**self.metas )["input_ids"] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained("openai/jukebox-5b-lyrics" ) A__ = tokenizer(**self.metas )["input_ids"] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
68
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
"""simple docstring""" import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser __UpperCamelCase = logging.getLogger(__name__) torch.set_grad_enabled(False) __UpperCamelCase = '''cuda''' if torch.cuda.is_available() else '''cpu''' def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=100 , UpperCAmelCase=" " ) -> List[str]: snake_case_ = text.split(UpperCAmelCase ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(UpperCAmelCase ) , UpperCAmelCase )] def UpperCAmelCase ( UpperCAmelCase ) -> dict: snake_case_ , snake_case_ = [], [] for title, text in zip(documents['title'] , documents['text'] ): if text is not None: for passage in split_text(UpperCAmelCase ): titles.append(title if title is not None else '' ) texts.append(UpperCAmelCase ) return {"title": titles, "text": texts} def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> dict: snake_case_ = ctx_tokenizer( documents['title'] , documents['text'] , truncation=UpperCAmelCase , padding='longest' , return_tensors='pt' )['input_ids'] snake_case_ = ctx_encoder(input_ids.to(device=UpperCAmelCase ) , return_dict=UpperCAmelCase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ) -> int: ###################################### logger.info('Step 1 - Create the dataset' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way snake_case_ = load_dataset( 'csv' , data_files=[rag_example_args.csv_path] , split='train' , delimiter='\t' , column_names=['title', 'text'] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words snake_case_ = dataset.map(UpperCAmelCase , batched=UpperCAmelCase , num_proc=processing_args.num_proc ) # And compute the embeddings snake_case_ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=UpperCAmelCase ) snake_case_ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) snake_case_ = Features( {'text': Value('string' ), 'title': Value('string' ), 'embeddings': Sequence(Value('float32' ) )} ) # optional, save as float32 instead of float64 to save space snake_case_ = dataset.map( partial(UpperCAmelCase , ctx_encoder=UpperCAmelCase , ctx_tokenizer=UpperCAmelCase ) , batched=UpperCAmelCase , batch_size=processing_args.batch_size , features=UpperCAmelCase , ) # And finally save your dataset snake_case_ = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset' ) dataset.save_to_disk(UpperCAmelCase ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('Step 2 - Index the dataset' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search snake_case_ = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('embeddings' , custom_index=UpperCAmelCase ) # And save the index snake_case_ = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset_hnsw_index.faiss' ) dataset.get_index('embeddings' ).save(UpperCAmelCase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class UpperCamelCase : SCREAMING_SNAKE_CASE_ = field( default=str(Path(lowerCAmelCase__ ).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv" ) , metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."} , ) SCREAMING_SNAKE_CASE_ = field( default="facebook/rag-sequence-nq" , metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"} , ) SCREAMING_SNAKE_CASE_ = field( default="facebook/dpr-ctx_encoder-multiset-base" , metadata={ "help": ( "The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or" " 'facebook/dpr-ctx_encoder-multiset-base'" ) } , ) SCREAMING_SNAKE_CASE_ = field( default=str(Path(lowerCAmelCase__ ).parent / "test_run" / "dummy-kb" ) , metadata={"help": "Path to a directory where the dataset passages and the index will be saved"} , ) @dataclass class UpperCamelCase : SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": "The number of processes to use to split the documents into passages. Default is single process." } , ) SCREAMING_SNAKE_CASE_ = field( default=1_6 , metadata={ "help": "The batch size to use when computing the passages embeddings using the DPR context encoder." } , ) @dataclass class UpperCamelCase : SCREAMING_SNAKE_CASE_ = field( default=7_6_8 , metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."} , ) SCREAMING_SNAKE_CASE_ = field( default=1_2_8 , metadata={ "help": ( "The number of bi-directional links created for every new element during the HNSW index construction." ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) __UpperCamelCase = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: __UpperCamelCase = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
69
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' 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 UpperCAmelCase : def __init__( self : List[str] , __snake_case : str , __snake_case : Dict=12 , __snake_case : Dict=7 , __snake_case : str=True , __snake_case : List[Any]=True , __snake_case : Dict=True , __snake_case : Optional[int]=99 , __snake_case : Dict=32 , __snake_case : Optional[Any]=32 , __snake_case : Union[str, Any]=2 , __snake_case : List[str]=4 , __snake_case : Optional[int]=37 , __snake_case : Union[str, Any]=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : int=5_12 , __snake_case : List[Any]=0.02 , __snake_case : Any=0 , __snake_case : List[Any]=None , ) -> int: _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 lowercase__ ( self : List[Any] ) -> List[str]: _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(__snake_case ): _lowerCAmelCase = 1 _lowerCAmelCase = 0 _lowerCAmelCase = self.get_config() return config, input_ids, tf.convert_to_tensor(__snake_case ) def lowercase__ ( self : List[str] ) -> Optional[int]: 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 lowercase__ ( self : int , __snake_case : Any , __snake_case : List[str] , __snake_case : List[Any] ) -> Optional[int]: _lowerCAmelCase = TFBlipTextModel(config=__snake_case ) _lowerCAmelCase = model(__snake_case , attention_mask=__snake_case , training=__snake_case ) _lowerCAmelCase = model(__snake_case , training=__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 lowercase__ ( self : Optional[int] ) -> Any: _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 UpperCAmelCase ( snake_case_ , unittest.TestCase ): _lowercase: str = (TFBlipTextModel,) if is_tf_available() else () _lowercase: Dict = False _lowercase: Dict = False _lowercase: Dict = False def lowercase__ ( self : List[Any] ) -> Optional[int]: _lowerCAmelCase = BlipTextModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase__ ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def lowercase__ ( self : int ) -> List[str]: _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase__ ( self : str ) -> Union[str, Any]: pass def lowercase__ ( self : Optional[Any] ) -> Tuple: pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def lowercase__ ( self : List[Any] ) -> List[Any]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def lowercase__ ( self : List[Any] ) -> List[str]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def lowercase__ ( self : List[str] ) -> int: pass @slow def lowercase__ ( self : List[str] ) -> List[str]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = TFBlipTextModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def lowercase__ ( self : List[str] , __snake_case : List[str]=True ) -> Any: super().test_pt_tf_model_equivalence(allow_missing_keys=__snake_case )
70
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Dict = logging.get_logger(__name__) A_ :Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __A ( a ): """simple docstring""" UpperCamelCase__ : Any ="""megatron-bert""" def __init__( self , lowerCamelCase__=29056 , lowerCamelCase__=1024 , lowerCamelCase__=24 , lowerCamelCase__=16 , lowerCamelCase__=4096 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=1E-12 , lowerCamelCase__=0 , lowerCamelCase__="absolute" , lowerCamelCase__=True , **lowerCamelCase__ , ): """simple docstring""" super().__init__(pad_token_id=lowerCamelCase__ , **lowerCamelCase__ ) __UpperCamelCase : List[str] =vocab_size __UpperCamelCase : Tuple =hidden_size __UpperCamelCase : Optional[int] =num_hidden_layers __UpperCamelCase : str =num_attention_heads __UpperCamelCase : int =hidden_act __UpperCamelCase : int =intermediate_size __UpperCamelCase : Optional[int] =hidden_dropout_prob __UpperCamelCase : List[Any] =attention_probs_dropout_prob __UpperCamelCase : List[str] =max_position_embeddings __UpperCamelCase : Optional[int] =type_vocab_size __UpperCamelCase : Optional[Any] =initializer_range __UpperCamelCase : Dict =layer_norm_eps __UpperCamelCase : Optional[int] =position_embedding_type __UpperCamelCase : Union[str, Any] =use_cache
71
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Swinv2ForImageClassification''', '''Swinv2ForMaskedImageModeling''', '''Swinv2Model''', '''Swinv2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """microsoft/trocr-base-handwritten""": ( """https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json""" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Tuple = '''trocr''' _UpperCAmelCase : int = ['''past_key_values'''] _UpperCAmelCase : Any = { '''num_attention_heads''': '''decoder_attention_heads''', '''hidden_size''': '''d_model''', '''num_hidden_layers''': '''decoder_layers''', } def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str=5_0_2_6_5 ,SCREAMING_SNAKE_CASE__ : int=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : List[str]=1_2 ,SCREAMING_SNAKE_CASE__ : str=1_6 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4_0_9_6 ,SCREAMING_SNAKE_CASE__ : str="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Tuple=0.1 ,SCREAMING_SNAKE_CASE__ : Tuple=0.0 ,SCREAMING_SNAKE_CASE__ : str=0.0 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Any=0.02 ,SCREAMING_SNAKE_CASE__ : Tuple=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=1 ,SCREAMING_SNAKE_CASE__ : str=0 ,SCREAMING_SNAKE_CASE__ : List[str]=2 ,**SCREAMING_SNAKE_CASE__ : int ,): __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : Union[str, Any] = decoder_layers __lowerCamelCase : Optional[int] = decoder_attention_heads __lowerCamelCase : str = decoder_ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : List[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : Any = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Optional[Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : Dict = use_cache __lowerCamelCase : Dict = scale_embedding __lowerCamelCase : List[str] = use_learned_position_embeddings __lowerCamelCase : int = layernorm_embedding super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ ,bos_token_id=SCREAMING_SNAKE_CASE__ ,eos_token_id=SCREAMING_SNAKE_CASE__ ,decoder_start_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,)
73
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" _lowercase = '''Tobias Carryer''' from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Dict=int(time() ) ) -> str: # noqa: B008 A = multiplier A = increment A = modulo A = seed def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. _lowercase = LinearCongruentialGenerator(1_66_45_25, 10_13_90_42_23, 2 << 31) while True: print(lcg.next_number())
74
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
'''simple docstring''' # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def a_ ( __snake_case : List[str] , __snake_case : int , __snake_case : Any , __snake_case : int ) -> int: """simple docstring""" lowerCamelCase_ ={ '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, nicht wahr?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] lowerCamelCase_ ={ '''wmt16-en-de-dist-12-1''': [2_8.3, 2_7.5_2], '''wmt16-en-de-dist-6-1''': [2_7.4, 2_7.1_1], '''wmt16-en-de-12-1''': [2_6.9, 2_5.7_5], } lowerCamelCase_ =F'''{src_lang}-{tgt_lang}''' lowerCamelCase_ =F''' --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt16 - allenai license: apache-2.0 datasets: - wmt16 metrics: - bleu --- # FSMT ## Model description This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}. For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369). All 3 models are available: * [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1) * [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1) * [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = "allenai/{model_name}" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = "{texts[src_lang]}" input_ids = tokenizer.encode(input, return_tensors="pt") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias ## Training data Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369). ## Eval results Here are the BLEU scores: model | fairseq | transformers -------|---------|---------- {model_name} | {scores[model_name][0]} | {scores[model_name][1]} The score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs. The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=5 mkdir -p $DATA_DIR sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` ## Data Sources - [training, etc.](http://www.statmt.org/wmt16/) - [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372) ### BibTeX entry and citation info ``` @misc{{kasai2020deep, title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}}, author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}}, year={{2020}}, eprint={{2006.10369}}, archivePrefix={{arXiv}}, primaryClass={{cs.CL}} }} ``` ''' model_card_dir.mkdir(parents=__snake_case , exist_ok=__snake_case ) lowerCamelCase_ =os.path.join(__snake_case , '''README.md''' ) print(F'''Generating {path}''' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(__snake_case ) # make sure we are under the root of the project a_ : List[Any] = Path(__file__).resolve().parent.parent.parent a_ : List[Any] = repo_dir / """model_cards""" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: a_ : Dict = model_cards_dir / """allenai""" / model_name write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)
75
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" super().tearDown() gc.collect() def __UpperCamelCase ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = FlaxStableDiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-2" , revision="bf16" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE : int = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Union[str, Any] = jax.device_count() SCREAMING_SNAKE_CASE : Optional[int] = num_samples * [prompt] SCREAMING_SNAKE_CASE : Any = sd_pipe.prepare_inputs(a ) SCREAMING_SNAKE_CASE : Tuple = replicate(a ) SCREAMING_SNAKE_CASE : Dict = shard(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : Dict = jax.random.split(a , jax.device_count() ) SCREAMING_SNAKE_CASE : str = sd_pipe(a , a , a , num_inference_steps=25 , jit=a )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE : List[str] = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE : Any = jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.4_5508, 0.4512] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = "stabilityai/stable-diffusion-2" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = FlaxDPMSolverMultistepScheduler.from_pretrained(a , subfolder="scheduler" ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = FlaxStableDiffusionPipeline.from_pretrained( a , scheduler=a , revision="bf16" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE : Tuple = scheduler_params SCREAMING_SNAKE_CASE : List[str] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Optional[Any] = jax.device_count() SCREAMING_SNAKE_CASE : int = num_samples * [prompt] SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.prepare_inputs(a ) SCREAMING_SNAKE_CASE : Tuple = replicate(a ) SCREAMING_SNAKE_CASE : Optional[int] = shard(a ) SCREAMING_SNAKE_CASE : Dict = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : str = jax.random.split(a , jax.device_count() ) SCREAMING_SNAKE_CASE : str = sd_pipe(a , a , a , num_inference_steps=25 , jit=a )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE : Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE : Union[str, Any] = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.array([0.4336, 0.4_2969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
76
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
"""simple docstring""" import argparse import copy def a_ ( _lowerCAmelCase : Optional[int] ): '''simple docstring''' lowercase__ : int = {} with open(_lowerCAmelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase__ : str = [] _list.append([line.split()[1], line.split()[2]] ) lowercase__ : Dict = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase__ : Dict = [] _list.append([line.split()[0], line.split()[2]] ) lowercase__ : Optional[int] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def a_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' with open(_lowerCAmelCase ) as f: lowercase__ : Union[str, Any] = f.read(1 ) lowercase__ : Union[str, Any] = start_node lowercase__ : int = [] lowercase__ : int = start_node lowercase__ : Optional[Any] = 0 while visiting not in first_solution: lowercase__ : str = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(_lowerCAmelCase ) and k[0] not in first_solution: lowercase__ : Any = k[1] lowercase__ : Union[str, Any] = k[0] first_solution.append(_lowerCAmelCase ) lowercase__ : Dict = distance_of_first_solution + int(_lowerCAmelCase ) lowercase__ : Tuple = best_node first_solution.append(_lowerCAmelCase ) lowercase__ : int = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase__ : str = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def a_ ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int ): '''simple docstring''' lowercase__ : Optional[int] = [] for n in solution[1:-1]: lowercase__ : int = solution.index(_lowerCAmelCase ) for kn in solution[1:-1]: lowercase__ : List[Any] = solution.index(_lowerCAmelCase ) if n == kn: continue lowercase__ : Optional[Any] = copy.deepcopy(_lowerCAmelCase ) lowercase__ : Tuple = kn lowercase__ : Dict = n lowercase__ : List[str] = 0 for k in _tmp[:-1]: lowercase__ : Optional[int] = _tmp[_tmp.index(_lowerCAmelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase__ : Optional[Any] = distance + int(i[1] ) _tmp.append(_lowerCAmelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase__ : Dict = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda _lowerCAmelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def a_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Tuple ): '''simple docstring''' lowercase__ : List[str] = 1 lowercase__ : Optional[int] = first_solution lowercase__ : List[Any] = [] lowercase__ : Optional[int] = distance_of_first_solution lowercase__ : List[str] = solution while count <= iters: lowercase__ : Any = find_neighborhood(_lowerCAmelCase , _lowerCAmelCase ) lowercase__ : Any = 0 lowercase__ : int = neighborhood[index_of_best_solution] lowercase__ : List[Any] = len(_lowerCAmelCase ) - 1 lowercase__ : List[str] = False while not found: lowercase__ : Optional[Any] = 0 while i < len(_lowerCAmelCase ): if best_solution[i] != solution[i]: lowercase__ : Union[str, Any] = best_solution[i] lowercase__ : Tuple = solution[i] break lowercase__ : str = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowercase__ : List[str] = True lowercase__ : List[str] = best_solution[:-1] lowercase__ : List[str] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase__ : List[Any] = cost lowercase__ : Tuple = solution else: lowercase__ : Tuple = index_of_best_solution + 1 lowercase__ : Any = neighborhood[index_of_best_solution] if len(_lowerCAmelCase ) >= size: tabu_list.pop(0 ) lowercase__ : List[Any] = count + 1 return best_solution_ever, best_cost def a_ ( _lowerCAmelCase : Tuple=None ): '''simple docstring''' lowercase__ : Tuple = generate_neighbours(args.File ) lowercase__ , lowercase__ : Optional[int] = generate_first_solution( args.File , _lowerCAmelCase ) lowercase__ , lowercase__ : Optional[int] = tabu_search( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , args.Iterations , args.Size , ) print(f"""Best solution: {best_sol}, with total distance: {best_cost}.""" ) if __name__ == "__main__": _UpperCamelCase : Optional[int] = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
77
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html snake_case_ = """platform""" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , ): if attention_mask is None: UpperCAmelCase = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: UpperCAmelCase = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: UpperCAmelCase = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class A_ : """simple docstring""" def __init__( self :Optional[int] , lowercase_ :Optional[int] , lowercase_ :List[str]=13 , lowercase_ :Optional[int]=7 , lowercase_ :Dict=True , lowercase_ :Union[str, Any]=False , lowercase_ :Optional[int]=99 , lowercase_ :Dict=16 , lowercase_ :List[Any]=2 , lowercase_ :str=4 , lowercase_ :Any=4 , lowercase_ :str="gelu" , lowercase_ :Optional[int]=0.1 , lowercase_ :int=0.1 , lowercase_ :Tuple=32 , lowercase_ :Tuple=2 , lowercase_ :List[str]=1 , lowercase_ :Dict=0 , lowercase_ :Optional[int]=0.02 , ) -> List[str]: UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = initializer_range def UpperCAmelCase__ ( self :int ) -> Dict: UpperCAmelCase = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) UpperCAmelCase = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) UpperCAmelCase = shift_tokens_right(lowercase_ , 1 , 2 ) UpperCAmelCase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowercase_ , ) UpperCAmelCase = prepare_blenderbot_inputs_dict(lowercase_ , lowercase_ , lowercase_ ) return config, inputs_dict def UpperCAmelCase__ ( self :str ) -> Any: UpperCAmelCase , UpperCAmelCase = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase__ ( self :int , lowercase_ :int , lowercase_ :str , lowercase_ :int ) -> Any: UpperCAmelCase = 20 UpperCAmelCase = model_class_name(lowercase_ ) UpperCAmelCase = model.encode(inputs_dict['input_ids'] ) UpperCAmelCase , UpperCAmelCase = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) UpperCAmelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) UpperCAmelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='i4' ) UpperCAmelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCAmelCase = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) UpperCAmelCase = model.decode( decoder_input_ids[:, -1:] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase_ , ) UpperCAmelCase = model.decode(lowercase_ , lowercase_ ) UpperCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) def UpperCAmelCase__ ( self :int , lowercase_ :Any , lowercase_ :List[str] , lowercase_ :Any ) -> Dict: UpperCAmelCase = 20 UpperCAmelCase = model_class_name(lowercase_ ) UpperCAmelCase = model.encode(inputs_dict['input_ids'] ) UpperCAmelCase , UpperCAmelCase = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) UpperCAmelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCAmelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) UpperCAmelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCAmelCase = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) UpperCAmelCase = model.decode( decoder_input_ids[:, -1:] , lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase = model.decode(lowercase_ , lowercase_ , decoder_attention_mask=lowercase_ ) UpperCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) @require_flax class A_ ( unittest.TestCase ): """simple docstring""" __UpperCamelCase = 99 def UpperCAmelCase__ ( self :List[Any] ) -> Any: UpperCAmelCase = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) UpperCAmelCase = input_ids.shape[0] UpperCAmelCase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCAmelCase__ ( self :Union[str, Any] ) -> Any: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = self._get_config_and_data() UpperCAmelCase = FlaxBlenderbotForConditionalGeneration(lowercase_ ) UpperCAmelCase = lm_model(input_ids=lowercase_ ) UpperCAmelCase = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['logits'].shape , lowercase_ ) def UpperCAmelCase__ ( self :Tuple ) -> Optional[int]: UpperCAmelCase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) UpperCAmelCase = FlaxBlenderbotForConditionalGeneration(lowercase_ ) UpperCAmelCase = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) UpperCAmelCase = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) UpperCAmelCase = lm_model(input_ids=lowercase_ , decoder_input_ids=lowercase_ ) UpperCAmelCase = (*summary.shape, config.vocab_size) self.assertEqual(outputs['logits'].shape , lowercase_ ) def UpperCAmelCase__ ( self :str ) -> List[Any]: UpperCAmelCase = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) UpperCAmelCase = shift_tokens_right(lowercase_ , 1 , 2 ) UpperCAmelCase = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() UpperCAmelCase = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowercase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class A_ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase , SCREAMING_SNAKE_CASE_ ): """simple docstring""" __UpperCamelCase = True __UpperCamelCase = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __UpperCamelCase = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def UpperCAmelCase__ ( self :Any ) -> Optional[int]: UpperCAmelCase = FlaxBlenderbotModelTester(self ) def UpperCAmelCase__ ( self :Dict ) -> Dict: UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase_ , lowercase_ , lowercase_ ) def UpperCAmelCase__ ( self :Tuple ) -> Dict: UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_ , lowercase_ , lowercase_ ) def UpperCAmelCase__ ( self :int ) -> Optional[Any]: UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCAmelCase = self._prepare_for_class(lowercase_ , lowercase_ ) UpperCAmelCase = model_class(lowercase_ ) @jax.jit def encode_jitted(lowercase_ :Dict , lowercase_ :Any=None , **lowercase_ :Optional[int] ): return model.encode(input_ids=lowercase_ , attention_mask=lowercase_ ) with self.subTest('JIT Enabled' ): UpperCAmelCase = encode_jitted(**lowercase_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCAmelCase = encode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase__ ( self :str ) -> Tuple: UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCAmelCase = model_class(lowercase_ ) UpperCAmelCase = model.encode(inputs_dict['input_ids'] , inputs_dict['attention_mask'] ) UpperCAmelCase = { 'decoder_input_ids': inputs_dict['decoder_input_ids'], 'decoder_attention_mask': inputs_dict['decoder_attention_mask'], 'encoder_outputs': encoder_outputs, } @jax.jit def decode_jitted(lowercase_ :str , lowercase_ :str , lowercase_ :Union[str, Any] ): return model.decode( decoder_input_ids=lowercase_ , decoder_attention_mask=lowercase_ , encoder_outputs=lowercase_ , ) with self.subTest('JIT Enabled' ): UpperCAmelCase = decode_jitted(**lowercase_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCAmelCase = decode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase__ ( self :List[Any] ) -> Optional[Any]: for model_class_name in self.all_model_classes: UpperCAmelCase = model_class_name.from_pretrained('facebook/blenderbot-400M-distill' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids UpperCAmelCase = np.ones((1, 1) ) * model.config.eos_token_id UpperCAmelCase = model(lowercase_ ) self.assertIsNotNone(lowercase_ ) @unittest.skipUnless(jax_device != 'cpu' , '3B test too slow on CPU.' ) @slow def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[Any]: UpperCAmelCase = {'num_beams': 1, 'early_stopping': True, 'min_length': 15, 'max_length': 25} UpperCAmelCase = {'skip_special_tokens': True, 'clean_up_tokenization_spaces': True} UpperCAmelCase = FlaxBlenderbotForConditionalGeneration.from_pretrained('facebook/blenderbot-3B' , from_pt=lowercase_ ) UpperCAmelCase = BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B' ) UpperCAmelCase = ['Sam'] UpperCAmelCase = tokenizer(lowercase_ , return_tensors='jax' ) UpperCAmelCase = model.generate(**lowercase_ , **lowercase_ ) UpperCAmelCase = 'Sam is a great name. It means "sun" in Gaelic.' UpperCAmelCase = tokenizer.batch_decode(lowercase_ , **lowercase_ ) assert generated_txt[0].strip() == tgt_text
78
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version lowerCamelCase_ = get_logger(__name__) class _UpperCAmelCase : """simple docstring""" snake_case = '''dummy_data''' snake_case = '''datasets''' snake_case = False def __init__( self : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : Union[Version, str] , __UpperCAmelCase : Optional[str] = None , __UpperCAmelCase : bool = False , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[List[Callable]] = None , ): '''simple docstring''' _A = 0 _A = dataset_name _A = cache_dir _A = use_local_dummy_data _A = config # download_callbacks take a single url as input _A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root _A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general _A = str(__UpperCAmelCase ) # to be downloaded _A = None _A = None @property def lowerCAmelCase ( self : List[str] ): '''simple docstring''' if self._dummy_file is None: _A = self.download_dummy_data() return self._dummy_file @property def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def lowerCAmelCase ( self : int ): '''simple docstring''' return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def lowerCAmelCase ( self : Dict ): '''simple docstring''' _A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) _A = cached_path( __UpperCAmelCase , cache_dir=self.cache_dir , extract_compressed_file=__UpperCAmelCase , force_extract=__UpperCAmelCase ) return os.path.join(__UpperCAmelCase , self.dummy_file_name ) @property def lowerCAmelCase ( self : List[str] ): '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def lowerCAmelCase ( self : int ): '''simple docstring''' if self._bucket_url is None: _A = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def lowerCAmelCase ( self : str ): '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[Any] , *__UpperCAmelCase : Dict ): '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested _A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned _A = self.dummy_file_name # special case when data_url is a dict if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.create_dummy_data_dict(__UpperCAmelCase , __UpperCAmelCase ) elif isinstance(__UpperCAmelCase , (list, tuple) ): return self.create_dummy_data_list(__UpperCAmelCase , __UpperCAmelCase ) else: return self.create_dummy_data_single(__UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[int] , *__UpperCAmelCase : Any ): '''simple docstring''' return self.download_and_extract(__UpperCAmelCase ) def lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str ): '''simple docstring''' return self.download_and_extract(__UpperCAmelCase ) def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[int] , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : List[str] ): '''simple docstring''' return path def lowerCAmelCase ( self : str ): '''simple docstring''' return {} def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : Optional[int] ): '''simple docstring''' _A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__UpperCAmelCase , __UpperCAmelCase ): for single_url in single_urls: download_callback(__UpperCAmelCase ) else: _A = single_urls download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__UpperCAmelCase , __UpperCAmelCase ): _A = [os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(Path(__UpperCAmelCase ).name ) ) for x in single_urls] else: _A = single_urls _A = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(Path(__UpperCAmelCase ).name ) ) _A = value # make sure that values are unique if all(isinstance(__UpperCAmelCase , __UpperCAmelCase ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique _A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] ): '''simple docstring''' _A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one _A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , __UpperCAmelCase ) ) for url in data_url ) _A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): _A = [data_url[0]] * len(__UpperCAmelCase ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _A = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(__UpperCAmelCase ) return dummy_data_list def lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] ): '''simple docstring''' for download_callback in self.download_callbacks: download_callback(__UpperCAmelCase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _A = os.path.join(__UpperCAmelCase , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(__UpperCAmelCase ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' pass def lowerCAmelCase ( self : Dict ): '''simple docstring''' pass def lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[Any] ): '''simple docstring''' def _iter_archive_members(__UpperCAmelCase : List[Any] ): # this preserves the order of the members inside the ZIP archive _A = Path(self.dummy_file ).parent _A = path.relative_to(__UpperCAmelCase ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: _A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__UpperCAmelCase ) _A = Path(__UpperCAmelCase ) _A = _iter_archive_members(__UpperCAmelCase ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(__UpperCAmelCase ).as_posix(), file_path.open("rb" ) def lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ): '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): _A = [paths] for path in paths: if os.path.isfile(__UpperCAmelCase ): if os.path.basename(__UpperCAmelCase ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__UpperCAmelCase ): if os.path.basename(__UpperCAmelCase ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(__UpperCAmelCase ): if filename.startswith((".", "__") ): continue yield os.path.join(__UpperCAmelCase , __UpperCAmelCase )
79
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class lowercase_ : def __init__( self , a ): UpperCamelCase__ = data UpperCamelCase__ = None class lowercase_ : def __init__( self ): UpperCamelCase__ = None UpperCamelCase__ = None def __iter__( self ): UpperCamelCase__ = self.head while self.head: yield node.data UpperCamelCase__ = node.next if node == self.head: break def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join(str(a ) for item in iter(self ) ) def __a ( self , a ): self.insert_nth(len(self ) , a ) def __a ( self , a ): self.insert_nth(0 , a ) def __a ( self , a , a ): if index < 0 or index > len(self ): raise IndexError("list index out of range." ) UpperCamelCase__ = Node(a ) if self.head is None: UpperCamelCase__ = new_node # first node points itself UpperCamelCase__ = UpperCamelCase__ = new_node elif index == 0: # insert at head UpperCamelCase__ = self.head UpperCamelCase__ = UpperCamelCase__ = new_node else: UpperCamelCase__ = self.head for _ in range(index - 1 ): UpperCamelCase__ = temp.next UpperCamelCase__ = temp.next UpperCamelCase__ = new_node if index == len(self ) - 1: # insert at tail UpperCamelCase__ = new_node def __a ( self ): return self.delete_nth(0 ) def __a ( self ): return self.delete_nth(len(self ) - 1 ) def __a ( self , a = 0 ): if not 0 <= index < len(self ): raise IndexError("list index out of range." ) UpperCamelCase__ = self.head if self.head == self.tail: # just one node UpperCamelCase__ = UpperCamelCase__ = None elif index == 0: # delete head node UpperCamelCase__ = self.tail.next.next UpperCamelCase__ = self.head.next else: UpperCamelCase__ = self.head for _ in range(index - 1 ): UpperCamelCase__ = temp.next UpperCamelCase__ = temp.next UpperCamelCase__ = temp.next.next if index == len(self ) - 1: # delete at tail UpperCamelCase__ = temp return delete_node.data def __a ( self ): return len(self ) == 0 def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = CircularLinkedList() assert len(__A ) == 0 assert circular_linked_list.is_empty() is True assert str(__A ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(__A ) == i circular_linked_list.insert_nth(__A , i + 1 ) assert str(__A ) == "->".join(str(__A ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(__A ) == "->".join(str(__A ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(__A ) == "->".join(str(__A ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(__A ) == "->".join(str(__A ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(__A ) == "->".join(str(__A ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
80
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : List[str] = { """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "sew-d" def __init__( self , __A=32 , __A=768 , __A=12 , __A=12 , __A=3072 , __A=2 , __A=512 , __A=256 , __A=True , __A=True , __A=("p2c", "c2p") , __A="layer_norm" , __A="gelu_python" , __A=0.1 , __A=0.1 , __A=0.1 , __A=0.0 , __A=0.1 , __A=0.02 , __A=1E-7 , __A=1E-5 , __A="group" , __A="gelu" , __A=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __A=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __A=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __A=False , __A=128 , __A=16 , __A=True , __A=0.05 , __A=10 , __A=2 , __A=0.0 , __A=10 , __A=0 , __A="mean" , __A=False , __A=False , __A=256 , __A=0 , __A=1 , __A=2 , **__A , ) -> Optional[Any]: super().__init__(**__A , pad_token_id=__A , bos_token_id=__A , eos_token_id=__A ) a =hidden_size a =feat_extract_norm a =feat_extract_activation a =list(__A ) a =list(__A ) a =list(__A ) a =conv_bias a =num_conv_pos_embeddings a =num_conv_pos_embedding_groups a =len(self.conv_dim ) a =num_hidden_layers a =intermediate_size a =squeeze_factor a =max_position_embeddings a =position_buckets a =share_att_key a =relative_attention a =norm_rel_ebd a =list(__A ) a =hidden_act a =num_attention_heads a =hidden_dropout a =attention_dropout a =activation_dropout a =feat_proj_dropout a =final_dropout a =layer_norm_eps a =feature_layer_norm_eps a =initializer_range a =vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect.''' '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,''' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a =apply_spec_augment a =mask_time_prob a =mask_time_length a =mask_time_min_masks a =mask_feature_prob a =mask_feature_length a =mask_feature_min_masks # ctc loss a =ctc_loss_reduction a =ctc_zero_infinity # sequence classification a =use_weighted_layer_sum a =classifier_proj_size @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: return functools.reduce(operator.mul , self.conv_stride , 1 )
81
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
from math import isqrt, loga def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , snake_case , snake_case ): _lowerCAmelCase = False return [i for i in range(2 , snake_case ) if is_prime[i]] def _UpperCAmelCase ( snake_case = 80_08_00 , snake_case = 80_08_00 ): """simple docstring""" _lowerCAmelCase = degree * loga(snake_case ) _lowerCAmelCase = int(snake_case ) _lowerCAmelCase = calculate_prime_numbers(snake_case ) _lowerCAmelCase = 0 _lowerCAmelCase = 0 _lowerCAmelCase = len(snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
82
'''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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
'''simple docstring''' from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function snake_case_ : int = 1.0_54_57_18_17e-34 # unit of ℏ : J * s snake_case_ : Optional[int] = 3e8 # unit of c : m * s^-1 def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): if (force, area, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if force < 0: raise ValueError('Magnitude of force can not be negative' ) if distance < 0: raise ValueError('Distance can not be negative' ) if area < 0: raise ValueError('Area can not be negative' ) if force == 0: _UpperCamelCase : Tuple = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_4_0 * (distance) ** 4 ) return {"force": force} elif area == 0: _UpperCamelCase : str = (2_4_0 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: _UpperCamelCase : Tuple = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_4_0 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('One and only one argument must be 0' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
83
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" import numpy # List of input, output pairs __UpperCAmelCase = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) __UpperCAmelCase = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) __UpperCAmelCase = [2, 4, 1, 5] __UpperCAmelCase = len(train_data) __UpperCAmelCase = 0.009 def _snake_case ( lowercase__ : List[str] , lowercase__ : str="train" ) -> Optional[int]: '''simple docstring''' return calculate_hypothesis_value(lowercase__ , lowercase__ ) - output( lowercase__ , lowercase__ ) def _snake_case ( lowercase__ : Optional[Any] ) -> List[Any]: '''simple docstring''' lowerCAmelCase_ :Union[str, Any] = 0 for i in range(len(lowercase__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _snake_case ( lowercase__ : str , lowercase__ : List[str] ) -> Optional[Any]: '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _snake_case ( lowercase__ : List[str] , lowercase__ : Optional[Any] ) -> List[str]: '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _snake_case ( lowercase__ : int , lowercase__ : int=m ) -> str: '''simple docstring''' lowerCAmelCase_ :str = 0 for i in range(lowercase__ ): if index == -1: summation_value += _error(lowercase__ ) else: summation_value += _error(lowercase__ ) * train_data[i][0][index] return summation_value def _snake_case ( lowercase__ : Optional[int] ) -> Any: '''simple docstring''' lowerCAmelCase_ :List[Any] = summation_of_cost_derivative(lowercase__ , lowercase__ ) / m return cost_derivative_value def _snake_case ( ) -> List[Any]: '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output lowerCAmelCase_ :Union[str, Any] = 0.000002 lowerCAmelCase_ :Optional[Any] = 0 lowerCAmelCase_ :int = 0 while True: j += 1 lowerCAmelCase_ :List[Any] = [0, 0, 0, 0] for i in range(0 , len(lowercase__ ) ): lowerCAmelCase_ :Any = get_cost_derivative(i - 1 ) lowerCAmelCase_ :Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( lowercase__ , lowercase__ , atol=lowercase__ , rtol=lowercase__ , ): break lowerCAmelCase_ :Optional[int] = temp_parameter_vector print(("""Number of iterations:""", j) ) def _snake_case ( ) -> Dict: '''simple docstring''' for i in range(len(lowercase__ ) ): print(("""Actual output value:""", output(lowercase__ , """test""" )) ) print(("""Hypothesis output:""", calculate_hypothesis_value(lowercase__ , """test""" )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
84
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, 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 UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
'''simple docstring''' from collections import namedtuple _SCREAMING_SNAKE_CASE : Optional[Any] = namedtuple("from_to", "from_ to") _SCREAMING_SNAKE_CASE : Dict = { "cubicmeter": from_to(1, 1), "litre": from_to(0.0_0_1, 1000), "kilolitre": from_to(1, 1), "gallon": from_to(0.0_0_4_5_4, 2_6_4.1_7_2), "cubicyard": from_to(0.7_6_4_5_5, 1.3_0_7_9_5), "cubicfoot": from_to(0.0_2_8, 3_5.3_1_4_7), "cup": from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def UpperCamelCase_( snake_case : float , snake_case : str , snake_case : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'from_type\' value: {from_type!r} Supported values are:\n' + ", ".join(snake_case ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'to_type\' value: {to_type!r}. Supported values are:\n' + ", ".join(snake_case ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import math def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = [] __lowerCAmelCase : Dict = 2 __lowerCAmelCase : Any = int(math.sqrt(_UpperCamelCase ) ) # Size of every segment __lowerCAmelCase : Tuple = [True] * (end + 1) __lowerCAmelCase : Any = [] while start <= end: if temp[start] is True: in_prime.append(_UpperCamelCase ) for i in range(start * start , end + 1 , _UpperCamelCase ): __lowerCAmelCase : int = False start += 1 prime += in_prime __lowerCAmelCase : Union[str, Any] = end + 1 __lowerCAmelCase : Tuple = min(2 * end , _UpperCamelCase ) while low <= n: __lowerCAmelCase : List[str] = [True] * (high - low + 1) for each in in_prime: __lowerCAmelCase : int = math.floor(low / each ) * each if t < low: t += each for j in range(_UpperCamelCase , high + 1 , _UpperCamelCase ): __lowerCAmelCase : Any = False for j in range(len(_UpperCamelCase ) ): if temp[j] is True: prime.append(j + low ) __lowerCAmelCase : Tuple = high + 1 __lowerCAmelCase : int = min(high + end , _UpperCamelCase ) return prime print(sieve(10**6))
86
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
def lowercase_ ( _lowerCamelCase : int): lowercase__ : Dict = [0] * len(_lowerCamelCase) lowercase__ : int = [] lowercase__ : List[str] = [1] * len(_lowerCamelCase) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_lowerCamelCase)): if indegree[i] == 0: queue.append(_lowerCamelCase) while queue: lowercase__ : Union[str, Any] = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowercase__ : Dict = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_lowerCamelCase) print(max(_lowerCamelCase)) # Adjacency list of Graph UpperCamelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
87
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = IFImgaImgSuperResolutionPipeline a__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""} a__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""} ) a__ = PipelineTesterMixin.required_optional_params - {"""latents"""} def _lowercase ( self : List[Any] ) -> Optional[int]: """simple docstring""" return self._get_superresolution_dummy_components() def _lowercase ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Dict=0 ) -> Any: """simple docstring""" if str(UpperCamelCase__ ).startswith("""mps""" ): __magic_name__ = torch.manual_seed(UpperCamelCase__ ) else: __magic_name__ = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) __magic_name__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) __magic_name__ = floats_tensor((1, 3, 16, 16) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) __magic_name__ = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def _lowercase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def _lowercase ( self : str ) -> Optional[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _lowercase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_save_load_local() def _lowercase ( self : str ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
88
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''caidas/swin2sr-classicalsr-x2-64''': ( '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : List[str] = 'swin2sr' lowerCAmelCase : str = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Union[str, Any] ,_UpperCAmelCase : Tuple=64 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : Any=180 ,_UpperCAmelCase : Optional[Any]=[6, 6, 6, 6, 6, 6] ,_UpperCAmelCase : Any=[6, 6, 6, 6, 6, 6] ,_UpperCAmelCase : int=8 ,_UpperCAmelCase : Any=2.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : Tuple=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Tuple=0.1 ,_UpperCAmelCase : List[str]="gelu" ,_UpperCAmelCase : Tuple=False ,_UpperCAmelCase : Optional[int]=0.02 ,_UpperCAmelCase : Union[str, Any]=1E-5 ,_UpperCAmelCase : int=2 ,_UpperCAmelCase : Tuple=1.0 ,_UpperCAmelCase : Union[str, Any]="1conv" ,_UpperCAmelCase : Tuple="pixelshuffle" ,**_UpperCAmelCase : List[str] ,): super().__init__(**_UpperCAmelCase ) _a : List[str] = image_size _a : Dict = patch_size _a : Optional[int] = num_channels _a : Optional[int] = embed_dim _a : Union[str, Any] = depths _a : Optional[int] = len(_UpperCAmelCase ) _a : Optional[Any] = num_heads _a : str = window_size _a : Optional[Any] = mlp_ratio _a : Optional[int] = qkv_bias _a : Tuple = hidden_dropout_prob _a : List[Any] = attention_probs_dropout_prob _a : Any = drop_path_rate _a : str = hidden_act _a : Tuple = use_absolute_embeddings _a : Dict = layer_norm_eps _a : Any = initializer_range _a : Optional[Any] = upscale _a : int = img_range _a : Union[str, Any] = resi_connection _a : int = upsampler
89
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCamelCase_ ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any]=10 ) -> str: """simple docstring""" __lowerCamelCase = [] for _ in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCamelCase_ ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any=10 ) -> Any: """simple docstring""" __lowerCamelCase = [] for step in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase = os.path.join(UpperCamelCase__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , UpperCamelCase__ ) __lowerCamelCase = torch.load(UpperCamelCase__ ) scheduler.load_state_dict(UpperCamelCase__ ) return lrs @require_torch class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: '''simple docstring''' self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) for a, b in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertAlmostEqual(lowerCamelCase__ , lowerCamelCase__ , delta=lowerCamelCase__ ) def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCamelCase__ ) __lowerCamelCase = torch.tensor([0.4, 0.2, -0.5] ) __lowerCamelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __lowerCamelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): __lowerCamelCase = criterion(lowerCamelCase__ , lowerCamelCase__ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCamelCase__ ) __lowerCamelCase = torch.tensor([0.4, 0.2, -0.5] ) __lowerCamelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __lowerCamelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=lowerCamelCase__ , weight_decay=0.0 , relative_step=lowerCamelCase__ , scale_parameter=lowerCamelCase__ , warmup_init=lowerCamelCase__ , ) for _ in range(1_000 ): __lowerCamelCase = criterion(lowerCamelCase__ , lowerCamelCase__ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" snake_case_ = nn.Linear(50 , 50 ) if is_torch_available() else None snake_case_ = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None snake_case_ = 10 def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Any: '''simple docstring''' self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) for a, b in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertAlmostEqual(lowerCamelCase__ , lowerCamelCase__ , delta=lowerCamelCase__ , msg=lowerCamelCase__ ) def lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) __lowerCamelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.6_56, 5.6_25, 3.9_06, 2.5, 1.4_06, 0.6_25, 0.1_56], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.1_65, 7.0_71, 6.3_25, 5.7_74, 5.3_45, 5.0, 4.7_14], ), } for scheduler_func, data in scheds.items(): __lowerCamelCase , __lowerCamelCase = data __lowerCamelCase = scheduler_func(self.optimizer , **lowerCamelCase__ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) __lowerCamelCase = unwrap_schedule(lowerCamelCase__ , self.num_steps ) self.assertListAlmostEqual( lowerCamelCase__ , lowerCamelCase__ , tol=1e-2 , msg=f"""failed for {scheduler_func} in normal scheduler""" , ) __lowerCamelCase = scheduler_func(self.optimizer , **lowerCamelCase__ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(lowerCamelCase__ ) # wrap to test picklability of the schedule __lowerCamelCase = unwrap_and_save_reload_schedule(lowerCamelCase__ , self.num_steps ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ , msg=f"""failed for {scheduler_func} in save and reload""" ) class __lowerCAmelCase : """simple docstring""" def __init__( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = fn def __call__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' return self.fn(*lowerCamelCase__ , **lowerCamelCase__ ) @classmethod def lowercase_ ( self , lowerCamelCase__ ) -> Any: '''simple docstring''' __lowerCamelCase = list(map(self , scheduler.lr_lambdas ) )
90
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": UpperCAmelCase_ : Tuple = input("""Enter image url: """).strip() print(f'''Downloading image from {url} ...''') UpperCAmelCase_ : int = BeautifulSoup(requests.get(url).content, """html.parser""") # The image URL is in the content field of the first meta tag with property og:image UpperCAmelCase_ : List[Any] = soup.find("""meta""", {"""property""": """og:image"""})["""content"""] UpperCAmelCase_ : List[Any] = requests.get(image_url).content UpperCAmelCase_ : str = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg''' with open(file_name, """wb""") as fp: fp.write(image_data) print(f'''Done. Image saved to disk as {file_name}.''')
91
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _a ( ): __lowerCAmelCase = ArgumentParser( description=( "PyTorch TPU distributed training launch " "helper utility that will spawn up " "multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=SCREAMING_SNAKE_CASE_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=SCREAMING_SNAKE_CASE_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=SCREAMING_SNAKE_CASE_ ) return parser.parse_args() def _a ( ): __lowerCAmelCase = parse_args() # Import training_script as a module. __lowerCAmelCase = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) __lowerCAmelCase = script_fpath.stem __lowerCAmelCase = importlib.import_module(SCREAMING_SNAKE_CASE_ ) # Patch sys.argv __lowerCAmelCase = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
92
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def snake_case_ ( __SCREAMING_SNAKE_CASE : bytes , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = F'''{sampling_rate}''' lowercase_ : Union[str, Any] = '''1''' lowercase_ : Optional[Any] = '''f32le''' lowercase_ : Optional[Any] = [ '''ffmpeg''', '''-i''', '''pipe:0''', '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] try: with subprocess.Popen(__SCREAMING_SNAKE_CASE , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: lowercase_ : List[str] = ffmpeg_process.communicate(__SCREAMING_SNAKE_CASE ) except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to load audio files from filename''' ) from error lowercase_ : int = output_stream[0] lowercase_ : Dict = np.frombuffer(__SCREAMING_SNAKE_CASE , np.floataa ) if audio.shape[0] == 0: raise ValueError('''Malformed soundfile''' ) return audio def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : str = "f32le" , ): """simple docstring""" lowercase_ : str = F'''{sampling_rate}''' lowercase_ : Optional[Any] = '''1''' if format_for_conversion == "s16le": lowercase_ : Any = 2 elif format_for_conversion == "f32le": lowercase_ : Optional[int] = 4 else: raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) lowercase_ : List[Any] = platform.system() if system == "Linux": lowercase_ : Optional[int] = '''alsa''' lowercase_ : Dict = '''default''' elif system == "Darwin": lowercase_ : int = '''avfoundation''' lowercase_ : str = ''':0''' elif system == "Windows": lowercase_ : int = '''dshow''' lowercase_ : Optional[Any] = '''default''' lowercase_ : Dict = [ '''ffmpeg''', '''-f''', format_, '''-i''', input_, '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-fflags''', '''nobuffer''', '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] lowercase_ : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample lowercase_ : int = _ffmpeg_stream(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for item in iterator: yield item def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : Optional[Union[Tuple[float, float], float]] = None , __SCREAMING_SNAKE_CASE : str = "f32le" , ): """simple docstring""" if stream_chunk_s is not None: lowercase_ : List[str] = stream_chunk_s else: lowercase_ : Optional[int] = chunk_length_s lowercase_ : List[Any] = ffmpeg_microphone(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , format_for_conversion=__SCREAMING_SNAKE_CASE ) if format_for_conversion == "s16le": lowercase_ : Tuple = np.intaa lowercase_ : Dict = 2 elif format_for_conversion == "f32le": lowercase_ : List[Any] = np.floataa lowercase_ : List[Any] = 4 else: raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) if stride_length_s is None: lowercase_ : List[str] = chunk_length_s / 6 lowercase_ : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(__SCREAMING_SNAKE_CASE , (int, float) ): lowercase_ : Tuple = [stride_length_s, stride_length_s] lowercase_ : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample lowercase_ : int = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample lowercase_ : Tuple = datetime.datetime.now() lowercase_ : Dict = datetime.timedelta(seconds=__SCREAMING_SNAKE_CASE ) for item in chunk_bytes_iter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=(stride_left, stride_right) , stream=__SCREAMING_SNAKE_CASE ): # Put everything back in numpy scale lowercase_ : int = np.frombuffer(item['''raw'''] , dtype=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = ( item['''stride'''][0] // size_of_sample, item['''stride'''][1] // size_of_sample, ) lowercase_ : Optional[Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple[int, int] , __SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" lowercase_ : Optional[int] = B'''''' lowercase_ , lowercase_ : Dict = stride if stride_left + stride_right >= chunk_len: raise ValueError( F'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''' ) lowercase_ : Any = 0 for raw in iterator: acc += raw if stream and len(__SCREAMING_SNAKE_CASE ) < chunk_len: lowercase_ : List[str] = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(__SCREAMING_SNAKE_CASE ) >= chunk_len: # We are flushing the accumulator lowercase_ : Tuple = (_stride_left, stride_right) lowercase_ : List[str] = {'''raw''': acc[:chunk_len], '''stride''': stride} if stream: lowercase_ : int = False yield item lowercase_ : Optional[Any] = stride_left lowercase_ : Union[str, Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(__SCREAMING_SNAKE_CASE ) > stride_left: lowercase_ : Union[str, Any] = {'''raw''': acc, '''stride''': (_stride_left, 0)} if stream: lowercase_ : Union[str, Any] = False yield item def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : str = 2**24 # 16Mo try: with subprocess.Popen(__SCREAMING_SNAKE_CASE , stdout=subprocess.PIPE , bufsize=__SCREAMING_SNAKE_CASE ) as ffmpeg_process: while True: lowercase_ : Any = ffmpeg_process.stdout.read(__SCREAMING_SNAKE_CASE ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to stream audio files from filename''' ) from error
93
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Union[str, Any] = logging.get_logger(__name__) snake_case : Tuple = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = 'vivit' def __init__( self , _lowerCamelCase=224 , _lowerCamelCase=32 , _lowerCamelCase=[2, 16, 16] , _lowerCamelCase=3 , _lowerCamelCase=768 , _lowerCamelCase=12 , _lowerCamelCase=12 , _lowerCamelCase=3072 , _lowerCamelCase="gelu_fast" , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.02 , _lowerCamelCase=1e-06 , _lowerCamelCase=True , **_lowerCamelCase , ): a :Optional[int] = hidden_size a :int = num_hidden_layers a :List[str] = num_attention_heads a :Any = intermediate_size a :Any = hidden_act a :int = hidden_dropout_prob a :Dict = attention_probs_dropout_prob a :Optional[Any] = initializer_range a :int = layer_norm_eps a :Optional[Any] = image_size a :Tuple = num_frames a :Optional[Any] = tubelet_size a :Union[str, Any] = num_channels a :int = qkv_bias super().__init__(**_lowerCamelCase )
94
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
95
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=64 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase=None , ): _lowerCamelCase : List[Any] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : List[str] = seq_length _lowerCamelCase : Dict = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : List[Any] = use_token_type_ids _lowerCamelCase : int = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Any = embedding_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Dict = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_act _lowerCamelCase : List[Any] = hidden_dropout_prob _lowerCamelCase : Union[str, Any] = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : List[str] = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Optional[Any] = initializer_range _lowerCamelCase : str = num_labels _lowerCamelCase : int = num_choices _lowerCamelCase : Any = scope def A_ ( self ): _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : int = None if self.use_input_mask: _lowerCamelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : Optional[Any] = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Dict = None _lowerCamelCase : Any = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A_ ( self ): return MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_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=lowercase , initializer_range=self.initializer_range , ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : Union[str, Any] = MobileBertModel(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : Optional[int] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase ) _lowerCamelCase : Union[str, Any] = model(lowercase , token_type_ids=lowercase ) _lowerCamelCase : List[str] = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : Union[str, Any] = MobileBertForMaskedLM(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : Optional[Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : List[Any] = MobileBertForNextSentencePrediction(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : List[str] = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : str = MobileBertForPreTraining(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : int = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , next_sentence_label=lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : Any = MobileBertForQuestionAnswering(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : str = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : List[str] = MobileBertForSequenceClassification(lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : str = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : Dict = self.num_labels _lowerCamelCase : Optional[int] = MobileBertForTokenClassification(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : Optional[Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): _lowerCamelCase : List[str] = self.num_choices _lowerCamelCase : Optional[int] = MobileBertForMultipleChoice(config=lowercase ) model.to(lowercase ) model.eval() _lowerCamelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Tuple = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A_ ( self ): _lowerCamelCase : Tuple = self.prepare_config_and_inputs() ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Tuple = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowercase, lowercase, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase__ = ( { """feature-extraction""": MobileBertModel, """fill-mask""": MobileBertForMaskedLM, """question-answering""": MobileBertForQuestionAnswering, """text-classification""": MobileBertForSequenceClassification, """token-classification""": MobileBertForTokenClassification, """zero-shot""": MobileBertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = True def A_ ( self , lowercase , lowercase , lowercase=False ): _lowerCamelCase : Optional[int] = super()._prepare_for_class(lowercase , lowercase , return_labels=lowercase ) if return_labels: if model_class in get_values(lowercase ): _lowerCamelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowercase ) _lowerCamelCase : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase ) return inputs_dict def A_ ( self ): _lowerCamelCase : int = MobileBertModelTester(self ) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=lowercase , hidden_size=37 ) def A_ ( self ): self.config_tester.run_common_tests() def A_ ( self ): _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*lowercase ) def A_ ( self ): _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*lowercase ) def A_ ( self ): _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*lowercase ) def A_ ( self ): _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*lowercase ) def A_ ( self ): _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*lowercase ) def A_ ( self ): _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*lowercase ) def A_ ( self ): _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*lowercase ) def A_ ( self ): _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*lowercase ) def _snake_case ( lowercase__ ): return torch.tensor( lowercase__ , dtype=torch.long , device=lowercase__ , ) lowercase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def A_ ( self ): _lowerCamelCase : Optional[int] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(lowercase ) _lowerCamelCase : Tuple = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): _lowerCamelCase : Any = model(lowercase )[0] _lowerCamelCase : Tuple = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , lowercase ) _lowerCamelCase : List[Any] = torch.tensor( [ [ [-2.473_6526E07, 8.269_1656E04, 1.652_1838E05], [-5.754_1704E-01, 3.905_6022E00, 4.401_1507E00], [2.604_7359E00, 1.567_7652E00, -1.732_4188E-01], ] ] , device=lowercase , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE _lowerCamelCase : Any = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) _lowerCamelCase : str = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
96
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = '''▁''' __snake_case = {'''vocab_file''': '''sentencepiece.bpe.model'''} __snake_case = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), } } __snake_case = { '''facebook/mbart-large-en-ro''': 1024, '''facebook/mbart-large-cc25''': 1024, } # fmt: off __snake_case = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class lowercase ( A__ ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = PRETRAINED_VOCAB_FILES_MAP _a = ['input_ids', 'attention_mask'] _a = [] _a = [] def __init__( self , UpperCamelCase_ , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_ = None , UpperCamelCase_=None , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :Dict = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token UpperCamelCase__ :int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , src_lang=UpperCamelCase_ , tgt_lang=UpperCamelCase_ , additional_special_tokens=UpperCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase_ , ) UpperCamelCase__ :int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCamelCase_ ) ) UpperCamelCase__ :Optional[int] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token UpperCamelCase__ :Dict = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCamelCase__ :Tuple = 1 UpperCamelCase__ :int = len(self.sp_model ) UpperCamelCase__ :Dict = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCamelCase_ ) } UpperCamelCase__ :List[Any] = {v: k for k, v in self.lang_code_to_id.items()} UpperCamelCase__ :Any = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) UpperCamelCase__ :Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} UpperCamelCase__ :Union[str, Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) UpperCamelCase__ :Any = src_lang if src_lang is not None else '''en_XX''' UpperCamelCase__ :Optional[Any] = self.lang_code_to_id[self._src_lang] UpperCamelCase__ :Union[str, Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): '''simple docstring''' UpperCamelCase__ :Dict = self.__dict__.copy() UpperCamelCase__ :int = None UpperCamelCase__ :Dict = self.sp_model.serialized_model_proto() return state def __setstate__( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCamelCase__ :Optional[int] = {} UpperCamelCase__ :Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self._src_lang @src_lang.setter def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) UpperCamelCase__ :List[str] = [1] * len(self.prefix_tokens ) UpperCamelCase__ :int = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCamelCase_ )) + suffix_ones return prefix_ones + ([0] * len(UpperCamelCase_ )) + ([0] * len(UpperCamelCase_ )) + suffix_ones def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' UpperCamelCase__ :Optional[int] = [self.sep_token_id] UpperCamelCase__ :List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) UpperCamelCase__ :Tuple = src_lang UpperCamelCase__ :Optional[Any] = self(UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase__ :List[str] = self.convert_tokens_to_ids(UpperCamelCase_ ) UpperCamelCase__ :Dict = tgt_lang_id return inputs def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Tuple = {self.convert_ids_to_tokens(UpperCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return self.sp_model.encode(UpperCamelCase_ , out_type=UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase__ :Any = self.sp_model.PieceToId(UpperCamelCase_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[str] = ''''''.join(UpperCamelCase_ ).replace(UpperCamelCase_ , ''' ''' ).strip() return out_string def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase__ :int = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase_ , '''wb''' ) as fi: UpperCamelCase__ :Any = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase_ ) return (out_vocab_file,) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = "en_XX" , UpperCamelCase_ = None , UpperCamelCase_ = "ro_RO" , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = src_lang UpperCamelCase__ :Optional[Any] = tgt_lang return super().prepare_seqaseq_batch(UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def lowerCAmelCase__ ( self ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Any = self.lang_code_to_id[src_lang] UpperCamelCase__ :int = [] UpperCamelCase__ :Union[str, Any] = [self.eos_token_id, self.cur_lang_code] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Dict = self.lang_code_to_id[lang] UpperCamelCase__ :Optional[Any] = [] UpperCamelCase__ :Tuple = [self.eos_token_id, self.cur_lang_code]
97
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
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 json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def a_ ( lowerCamelCase ): UpperCAmelCase__ = botoa.client('iam' ) UpperCAmelCase__ = { 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=lowerCamelCase , AssumeRolePolicyDocument=json.dumps(lowerCamelCase , indent=2 ) ) UpperCAmelCase__ = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=lowerCamelCase , PolicyName=f'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(lowerCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f'''role {role_name} already exists. Using existing one''' ) def a_ ( lowerCamelCase ): UpperCAmelCase__ = botoa.client('iam' ) return iam_client.get_role(RoleName=lowerCamelCase )["Role"]["Arn"] def a_ ( ): UpperCAmelCase__ = _ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , lowerCamelCase , ) UpperCAmelCase__ = None if credentials_configuration == 0: UpperCAmelCase__ = _ask_field('Enter your AWS Profile name: [default] ' , default='default' ) UpperCAmelCase__ = aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) UpperCAmelCase__ = _ask_field('AWS Access Key ID: ' ) UpperCAmelCase__ = aws_access_key_id UpperCAmelCase__ = _ask_field('AWS Secret Access Key: ' ) UpperCAmelCase__ = aws_secret_access_key UpperCAmelCase__ = _ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) UpperCAmelCase__ = aws_region UpperCAmelCase__ = _ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , lowerCamelCase , ) if role_management == 0: UpperCAmelCase__ = _ask_field('Enter your IAM role name: ' ) else: UpperCAmelCase__ = 'accelerate_sagemaker_execution_role' print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(lowerCamelCase ) UpperCAmelCase__ = _ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) UpperCAmelCase__ = None if is_custom_docker_image: UpperCAmelCase__ = _ask_field('Enter your Docker image: ' , lambda lowerCamelCase : str(lowerCamelCase ).lower() ) UpperCAmelCase__ = _ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) UpperCAmelCase__ = None if is_sagemaker_inputs_enabled: UpperCAmelCase__ = _ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda lowerCamelCase : str(lowerCamelCase ).lower() , ) UpperCAmelCase__ = _ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) UpperCAmelCase__ = None if is_sagemaker_metrics_enabled: UpperCAmelCase__ = _ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda lowerCamelCase : str(lowerCamelCase ).lower() , ) UpperCAmelCase__ = _ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) UpperCAmelCase__ = {} UpperCAmelCase__ = _ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: UpperCAmelCase__ = 'dynamo_' UpperCAmelCase__ = _ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) UpperCAmelCase__ = _ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: UpperCAmelCase__ = _ask_options( 'Which mode do you want to use?' , lowerCamelCase , lambda lowerCamelCase : TORCH_DYNAMO_MODES[int(lowerCamelCase )] , default='default' , ) UpperCAmelCase__ = _ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) UpperCAmelCase__ = _ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=lowerCamelCase , error_message='Please enter yes or no.' , ) UpperCAmelCase__ = 'Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: UpperCAmelCase__ = _ask_options( lowerCamelCase , lowerCamelCase , lambda lowerCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(lowerCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" UpperCAmelCase__ = _ask_field(lowerCamelCase , lambda lowerCamelCase : str(lowerCamelCase ).lower() , default='ml.p3.2xlarge' ) UpperCAmelCase__ = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): UpperCAmelCase__ = _ask_field( 'How many machines do you want use? [1]: ' , lowerCamelCase , default=1 , ) UpperCAmelCase__ = _ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=lowerCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=lowerCamelCase , use_cpu=lowerCamelCase , dynamo_config=lowerCamelCase , eca_instance_type=lowerCamelCase , profile=lowerCamelCase , region=lowerCamelCase , iam_role_name=lowerCamelCase , mixed_precision=lowerCamelCase , num_machines=lowerCamelCase , sagemaker_inputs_file=lowerCamelCase , sagemaker_metrics_file=lowerCamelCase , )
98
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=13 , lowercase=64 , lowercase=2 , lowercase=3 , lowercase=True , lowercase=True , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=10 , lowercase=0.02 , lowercase=[1, 16, 4, 4] , lowercase=None , ) -> List[Any]: '''simple docstring''' a__ : Optional[int] = parent a__ : Optional[int] = batch_size a__ : Any = image_size a__ : Optional[Any] = patch_size a__ : Optional[Any] = num_channels a__ : int = is_training a__ : List[str] = use_labels a__ : List[str] = hidden_size a__ : Tuple = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : Optional[int] = hidden_act a__ : Optional[Any] = hidden_dropout_prob a__ : Any = attention_probs_dropout_prob a__ : Any = type_sequence_label_size a__ : Tuple = initializer_range a__ : Tuple = scope a__ : int = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size a__ : Any = (self.image_size // 32) ** 2 a__ : List[Any] = num_patches + 1 def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a__ : int = None if self.use_labels: a__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : List[str] = self.get_config() return config, pixel_values, labels def __lowercase ( self) -> Dict: '''simple docstring''' a__ : List[str] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [4, 8, 16, 32], 'num_groups': 2, } return ViTHybridConfig( 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=lowercase , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=lowercase , ) def __lowercase ( self , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : List[str] = ViTHybridModel(config=lowercase) model.to(lowercase) model.eval() a__ : Union[str, Any] = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowercase ( self , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : Dict = self.type_sequence_label_size a__ : Union[str, Any] = ViTHybridForImageClassification(lowercase) model.to(lowercase) model.eval() a__ : Tuple = model(lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = self.prepare_config_and_inputs() a__ , a__ , a__ : Union[str, Any] = config_and_inputs a__ : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Optional[Any] = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () __A : List[str] = ( {'''feature-extraction''': ViTHybridModel, '''image-classification''': ViTHybridForImageClassification} if is_torch_available() else {} ) __A : Any = False __A : Optional[int] = False __A : Optional[Any] = False def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Any = ViTHybridModelTester(self) a__ : Any = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37) def __lowercase ( self) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds') def __lowercase ( self) -> Dict: '''simple docstring''' pass def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ , a__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : str = model_class(lowercase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) a__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase , nn.Linear)) def __lowercase ( self) -> int: '''simple docstring''' a__ , a__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Union[str, Any] = model_class(lowercase) a__ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[Any] = [*signature.parameters.keys()] a__ : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase) def __lowercase ( self) -> Dict: '''simple docstring''' a__ , a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a__ : Tuple = _config_zero_init(lowercase) for model_class in self.all_model_classes: a__ : List[Any] = model_class(config=lowercase) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": a__ : Dict = [F'{name}.{key}' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue 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' , ) @slow def __lowercase ( self) -> Any: '''simple docstring''' for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = ViTHybridModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) def A_ ( ) -> int: a__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self) -> Optional[Any]: '''simple docstring''' return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase) a__ : List[str] = self.default_image_processor a__ : List[Any] = prepare_img() a__ : Any = image_processor(images=lowercase , return_tensors='pt').to(lowercase) # forward pass with torch.no_grad(): a__ : Optional[Any] = model(**lowercase) # verify the logits a__ : Optional[Any] = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase) a__ : Any = torch.tensor([-1.90_90, -0.49_93, -0.23_89]).to(lowercase) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1e-4)) @slow @require_accelerate def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : List[str] = ViTHybridImageProcessor.from_pretrained('google/vit-hybrid-base-bit-384') a__ : Union[str, Any] = ViTHybridForImageClassification.from_pretrained('google/vit-hybrid-base-bit-384' , device_map='auto') a__ : Any = prepare_img() a__ : str = image_processor(images=lowercase , return_tensors='pt') a__ : List[Any] = model(**lowercase) a__ : int = outputs.logits # model predicts one of the 1000 ImageNet classes a__ : List[str] = logits.argmax(-1).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , 'tabby, tabby cat')
99
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __magic_name__ = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "layers_per_block": 2, "num_class_embeds": 1000, "block_out_channels": [32, 64], "attention_head_dim": 8, "down_block_types": [ "ResnetDownsampleBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "scale_shift", "upsample_type": "resnet", "downsample_type": "resnet", } __magic_name__ = { "sample_size": 64, "in_channels": 3, "out_channels": 3, "layers_per_block": 3, "num_class_embeds": 1000, "block_out_channels": [192, 192 * 2, 192 * 3, 192 * 4], "attention_head_dim": 64, "down_block_types": [ "ResnetDownsampleBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "scale_shift", "upsample_type": "resnet", "downsample_type": "resnet", } __magic_name__ = { "sample_size": 256, "in_channels": 3, "out_channels": 3, "layers_per_block": 2, "num_class_embeds": None, "block_out_channels": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], "attention_head_dim": 64, "down_block_types": [ "ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "default", "upsample_type": "resnet", "downsample_type": "resnet", } __magic_name__ = { "num_train_timesteps": 40, "sigma_min": 0.002, "sigma_max": 80.0, } __magic_name__ = { "num_train_timesteps": 201, "sigma_min": 0.002, "sigma_max": 80.0, } __magic_name__ = { "num_train_timesteps": 151, "sigma_min": 0.002, "sigma_max": 80.0, } def _lowerCAmelCase ( UpperCamelCase_ ): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("""boolean value expected""" ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=False ): __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.in_layers.0.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.in_layers.0.bias"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.in_layers.2.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.in_layers.2.bias"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.emb_layers.1.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.emb_layers.1.bias"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.out_layers.0.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.out_layers.0.bias"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.out_layers.3.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.out_layers.3.bias"] if has_skip: __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.skip_connection.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.skip_connection.bias"] return new_checkpoint def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.norm.weight"] __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.norm.bias"] __SCREAMING_SNAKE_CASE = weight_q.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = bias_q.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = weight_k.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = bias_k.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = weight_v.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = bias_v.squeeze(-1 ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = ( checkpoint[f"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) __SCREAMING_SNAKE_CASE = checkpoint[f"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = torch.load(UpperCamelCase_ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = checkpoint["""time_embed.0.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""time_embed.0.bias"""] __SCREAMING_SNAKE_CASE = checkpoint["""time_embed.2.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""time_embed.2.bias"""] if unet_config["num_class_embeds"] is not None: __SCREAMING_SNAKE_CASE = checkpoint["""label_emb.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""input_blocks.0.0.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""input_blocks.0.0.bias"""] __SCREAMING_SNAKE_CASE = unet_config["""down_block_types"""] __SCREAMING_SNAKE_CASE = unet_config["""layers_per_block"""] __SCREAMING_SNAKE_CASE = unet_config["""attention_head_dim"""] __SCREAMING_SNAKE_CASE = unet_config["""block_out_channels"""] __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = channels_list[0] for i, layer_type in enumerate(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = channels_list[i] __SCREAMING_SNAKE_CASE = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = f"down_blocks.{i}.resnets.{j}" __SCREAMING_SNAKE_CASE = f"input_blocks.{current_layer}.0" __SCREAMING_SNAKE_CASE = True if j == 0 and downsample_block_has_skip else False __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , has_skip=UpperCamelCase_ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = f"down_blocks.{i}.resnets.{j}" __SCREAMING_SNAKE_CASE = f"input_blocks.{current_layer}.0" __SCREAMING_SNAKE_CASE = True if j == 0 and downsample_block_has_skip else False __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , has_skip=UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = f"down_blocks.{i}.attentions.{j}" __SCREAMING_SNAKE_CASE = f"input_blocks.{current_layer}.1" __SCREAMING_SNAKE_CASE = convert_attention( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) current_layer += 1 if i != len(UpperCamelCase_ ) - 1: __SCREAMING_SNAKE_CASE = f"down_blocks.{i}.downsamplers.0" __SCREAMING_SNAKE_CASE = f"input_blocks.{current_layer}.0" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) current_layer += 1 __SCREAMING_SNAKE_CASE = current_channels # hardcoded the mid-block for now __SCREAMING_SNAKE_CASE = """mid_block.resnets.0""" __SCREAMING_SNAKE_CASE = """middle_block.0""" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = """mid_block.attentions.0""" __SCREAMING_SNAKE_CASE = """middle_block.1""" __SCREAMING_SNAKE_CASE = convert_attention(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = """mid_block.resnets.1""" __SCREAMING_SNAKE_CASE = """middle_block.2""" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = unet_config["""up_block_types"""] for i, layer_type in enumerate(UpperCamelCase_ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): __SCREAMING_SNAKE_CASE = f"up_blocks.{i}.resnets.{j}" __SCREAMING_SNAKE_CASE = f"output_blocks.{current_layer}.0" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , has_skip=UpperCamelCase_ ) current_layer += 1 if i != len(UpperCamelCase_ ) - 1: __SCREAMING_SNAKE_CASE = f"up_blocks.{i}.upsamplers.0" __SCREAMING_SNAKE_CASE = f"output_blocks.{current_layer-1}.1" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): __SCREAMING_SNAKE_CASE = f"up_blocks.{i}.resnets.{j}" __SCREAMING_SNAKE_CASE = f"output_blocks.{current_layer}.0" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , has_skip=UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = f"up_blocks.{i}.attentions.{j}" __SCREAMING_SNAKE_CASE = f"output_blocks.{current_layer}.1" __SCREAMING_SNAKE_CASE = convert_attention( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) current_layer += 1 if i != len(UpperCamelCase_ ) - 1: __SCREAMING_SNAKE_CASE = f"up_blocks.{i}.upsamplers.0" __SCREAMING_SNAKE_CASE = f"output_blocks.{current_layer-1}.2" __SCREAMING_SNAKE_CASE = convert_resnet(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = checkpoint["""out.0.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""out.0.bias"""] __SCREAMING_SNAKE_CASE = checkpoint["""out.2.weight"""] __SCREAMING_SNAKE_CASE = checkpoint["""out.2.bias"""] return new_checkpoint if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() parser.add_argument("--unet_path", default=None, type=str, required=True, help="Path to the unet.pt to convert.") parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output the converted UNet model." ) parser.add_argument("--class_cond", default=True, type=str, help="Whether the model is class-conditional.") __magic_name__ = parser.parse_args() __magic_name__ = strabool(args.class_cond) __magic_name__ = os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: __magic_name__ = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __magic_name__ = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: __magic_name__ = TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: __magic_name__ = None __magic_name__ = con_pt_to_diffuser(args.unet_path, unet_config) __magic_name__ = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: __magic_name__ = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: __magic_name__ = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __magic_name__ = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") __magic_name__ = CMStochasticIterativeScheduler(**scheduler_config) __magic_name__ = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
100
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0