code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import argparse import struct import unittest class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[str] , __a : List[Any] ): _a = data # Initialize hash values _a = [ 0X6A_09_E6_67, 0XBB_67_AE_85, 0X3C_6E_F3_72, 0XA5_4F_F5_3A, 0X51_0E_52_7F, 0X9B_05_68_8C, 0X1F_83_D9_AB, 0X5B_E0_CD_19, ] # Initialize round constants _a = [ 0X42_8A_2F_98, 0X71_37_44_91, 0XB5_C0_FB_CF, 0XE9_B5_DB_A5, 0X39_56_C2_5B, 0X59_F1_11_F1, 0X92_3F_82_A4, 0XAB_1C_5E_D5, 0XD8_07_AA_98, 0X12_83_5B_01, 0X24_31_85_BE, 0X55_0C_7D_C3, 0X72_BE_5D_74, 0X80_DE_B1_FE, 0X9B_DC_06_A7, 0XC1_9B_F1_74, 0XE4_9B_69_C1, 0XEF_BE_47_86, 0X0F_C1_9D_C6, 0X24_0C_A1_CC, 0X2D_E9_2C_6F, 0X4A_74_84_AA, 0X5C_B0_A9_DC, 0X76_F9_88_DA, 0X98_3E_51_52, 0XA8_31_C6_6D, 0XB0_03_27_C8, 0XBF_59_7F_C7, 0XC6_E0_0B_F3, 0XD5_A7_91_47, 0X06_CA_63_51, 0X14_29_29_67, 0X27_B7_0A_85, 0X2E_1B_21_38, 0X4D_2C_6D_FC, 0X53_38_0D_13, 0X65_0A_73_54, 0X76_6A_0A_BB, 0X81_C2_C9_2E, 0X92_72_2C_85, 0XA2_BF_E8_A1, 0XA8_1A_66_4B, 0XC2_4B_8B_70, 0XC7_6C_51_A3, 0XD1_92_E8_19, 0XD6_99_06_24, 0XF4_0E_35_85, 0X10_6A_A0_70, 0X19_A4_C1_16, 0X1E_37_6C_08, 0X27_48_77_4C, 0X34_B0_BC_B5, 0X39_1C_0C_B3, 0X4E_D8_AA_4A, 0X5B_9C_CA_4F, 0X68_2E_6F_F3, 0X74_8F_82_EE, 0X78_A5_63_6F, 0X84_C8_78_14, 0X8C_C7_02_08, 0X90_BE_FF_FA, 0XA4_50_6C_EB, 0XBE_F9_A3_F7, 0XC6_71_78_F2, ] _a = self.preprocessing(self.data ) self.final_hash() @staticmethod def UpperCamelCase__ ( __a : Tuple ): _a = B"\x80" + (B"\x00" * (63 - (len(_SCREAMING_SNAKE_CASE ) + 8) % 64)) _a = struct.pack(">Q" , (len(_SCREAMING_SNAKE_CASE ) * 8) ) return data + padding + big_endian_integer def UpperCamelCase__ ( self : Optional[Any] ): # Convert into blocks of 64 bytes _a = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers _a = list(struct.unpack(">16L" , _SCREAMING_SNAKE_CASE ) ) # add 48 0-ed integers words += [0] * 48 _a , _a , _a , _a , _a , _a , _a , _a = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array _a = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) _a = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) _a = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_00_00_00_00 # Compression _a = self.ror(_SCREAMING_SNAKE_CASE , 6 ) ^ self.ror(_SCREAMING_SNAKE_CASE , 11 ) ^ self.ror(_SCREAMING_SNAKE_CASE , 25 ) _a = (e & f) ^ ((~e & 0XFF_FF_FF_FF) & g) _a = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_00_00_00_00 _a = self.ror(_SCREAMING_SNAKE_CASE , 2 ) ^ self.ror(_SCREAMING_SNAKE_CASE , 13 ) ^ self.ror(_SCREAMING_SNAKE_CASE , 22 ) _a = (a & b) ^ (a & c) ^ (b & c) _a = (sa + maj) % 0X1_00_00_00_00 _a , _a , _a , _a , _a , _a , _a , _a = ( g, f, e, ((d + tempa) % 0X1_00_00_00_00), c, b, a, ((tempa + tempa) % 0X1_00_00_00_00), ) _a = [a, b, c, d, e, f, g, h] # Modify final values _a = [ ((element + mutated_hash_values[index]) % 0X1_00_00_00_00) for index, element in enumerate(self.hashes ) ] _a = "".join([hex(_SCREAMING_SNAKE_CASE )[2:].zfill(8 ) for value in self.hashes] ) def UpperCamelCase__ ( self : int , __a : int , __a : Dict ): return 0XFF_FF_FF_FF & (value << (32 - rotations)) | (value >> rotations) class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): import hashlib _a = bytes("Test String" , "utf-8" ) self.assertEqual(SHAaaa(_SCREAMING_SNAKE_CASE ).hash , hashlib.shaaaa(_SCREAMING_SNAKE_CASE ).hexdigest() ) def _lowerCamelCase ( ) -> None: import doctest doctest.testmod() _a = argparse.ArgumentParser() parser.add_argument( "-s" , "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument( "-f" , "--file" , dest="input_file" , help="Hash contents of a file" ) _a = parser.parse_args() _a = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: _a = f.read() else: _a = bytes(_A , "utf-8" ) print(SHAaaa(_A ).hash ) if __name__ == "__main__": main()
355
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCamelCase ( ) -> str: _a = HfArgumentParser(lowercase ) _a = parser.parse_args_into_dataclasses()[0] _a = TensorFlowBenchmark(args=lowercase ) try: _a = parser.parse_args_into_dataclasses()[0] except ValueError as e: _a = "Arg --no_{0} is no longer used, please use --no-{0} instead." _a = " ".join(str(lowercase ).split(" " )[:-1] ) _a = "" _a = eval(str(lowercase ).split(" " )[-1] ) _a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowercase ) if len(lowercase ) > 0: _a = full_error_msg + begin_error_msg + str(lowercase ) raise ValueError(lowercase ) benchmark.run() if __name__ == "__main__": main()
346
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : Tuple = { 'google/mobilenet_v2_1.4_224': 'https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json', 'google/mobilenet_v2_1.0_224': 'https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json', 'google/mobilenet_v2_0.75_160': 'https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json', 'google/mobilenet_v2_0.35_96': 'https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json', # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class __SCREAMING_SNAKE_CASE (snake_case_ ): """simple docstring""" __a ='mobilenet_v2' def __init__( self : Optional[int] , __a : str=3 , __a : List[Any]=2_24 , __a : List[Any]=1.0 , __a : Optional[int]=8 , __a : Dict=8 , __a : Optional[int]=6 , __a : Dict=32 , __a : Optional[Any]=True , __a : Any=True , __a : str="relu6" , __a : Dict=True , __a : Union[str, Any]=0.8 , __a : Optional[Any]=0.02 , __a : List[str]=0.001 , __a : Tuple=2_55 , **__a : Optional[Any] , ): super().__init__(**__a ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) _a = num_channels _a = image_size _a = depth_multiplier _a = depth_divisible_by _a = min_depth _a = expand_ratio _a = output_stride _a = first_layer_is_expansion _a = finegrained_output _a = hidden_act _a = tf_padding _a = classifier_dropout_prob _a = initializer_range _a = layer_norm_eps _a = semantic_loss_ignore_index class __SCREAMING_SNAKE_CASE (snake_case_ ): """simple docstring""" __a =version.parse('1.11' ) @property def UpperCamelCase__ ( self : Optional[int] ): return OrderedDict([("pixel_values", {0: "batch"})] ) @property def UpperCamelCase__ ( self : str ): if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def UpperCamelCase__ ( self : Optional[Any] ): return 1e-4
356
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ : Union[str, Any] = None try: import msvcrt except ImportError: lowerCAmelCase_ : Tuple = None try: import fcntl except ImportError: lowerCAmelCase_ : Optional[int] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ : Any = OSError # Data # ------------------------------------------------ lowerCAmelCase_ : Tuple = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] lowerCAmelCase_ : Optional[int] = '3.0.12' lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( ) -> Optional[int]: global _logger _a = _logger or logging.getLogger(__name__ ) return _logger class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict , __a : Optional[Any] ): _a = lock_file return None def __str__( self : Any ): _a = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , __a : Optional[int] ): _a = lock return None def __enter__( self : str ): return self.lock def __exit__( self : List[Any] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): self.lock.release() return None class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] , __a : Optional[int]=-1 , __a : Tuple=None ): _a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long _a = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. _a = 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. _a = None # The default timeout value. _a = timeout # We use this lock primarily for the lock counter. _a = 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. _a = 0 return None @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file @property def UpperCamelCase__ ( self : List[Any] ): return self._timeout @timeout.setter def UpperCamelCase__ ( self : int , __a : List[Any] ): _a = float(__a ) return None def UpperCamelCase__ ( self : Dict ): raise NotImplementedError() def UpperCamelCase__ ( self : str ): raise NotImplementedError() @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file_fd is not None def UpperCamelCase__ ( self : int , __a : int=None , __a : Tuple=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: _a = 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 _a = id(self ) _a = self._lock_file _a = 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(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: _a = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: _a = id(self ) _a = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() _a = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : List[Any] ): self.acquire() return self def __exit__( self : str , __a : str , __a : Dict , __a : Dict ): self.release() return None def __del__( self : int ): self.release(force=__a ) return None def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): _a = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: _a = os.path.dirname(__a ) _a = str(hash(__a ) ) _a = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , __a : str , __a : List[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) _a = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def UpperCamelCase__ ( self : int ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Optional[Any] ): _a = self._lock_file_fd _a = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=-1 , __a : int=None ): _a = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def UpperCamelCase__ ( self : Any ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC _a = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Tuple ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition _a = self._lock_file_fd _a = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): _a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: _a = fd return None def UpperCamelCase__ ( self : Union[str, Any] ): os.close(self._lock_file_fd ) _a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ : str = None if msvcrt: lowerCAmelCase_ : List[str] = WindowsFileLock elif fcntl: lowerCAmelCase_ : List[str] = UnixFileLock else: lowerCAmelCase_ : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int ) -> Optional[int]: if not isinstance(lowercase , lowercase ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) _a = 0 _a = str(lowercase ) while len(lowercase ) != 1: _a = [int(lowercase ) for i in num_string] _a = 1 for i in range(0 , len(lowercase ) ): total *= numbers[i] _a = str(lowercase ) steps += 1 return steps def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: if not isinstance(lowercase , lowercase ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) _a = 0 _a = str(lowercase ) while len(lowercase ) != 1: _a = [int(lowercase ) for i in num_string] _a = 0 for i in range(0 , len(lowercase ) ): total += numbers[i] _a = str(lowercase ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
357
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *__a : List[str] , **__a : Optional[Any] ): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , lowercase__ , ) super().__init__(*lowercase__ , **lowercase__ )
358
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ : List[str] = TypeVar('T') lowerCAmelCase_ : Dict = TypeVar('U') class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Union[str, Any] , __a : T | None , __a : U | None ): _a = key _a = val _a = None _a = None def __repr__( self : Any ): return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Dict ): _a = DoubleLinkedListNode(__a , __a ) _a = DoubleLinkedListNode(__a , __a ) _a , _a = self.rear, self.head def __repr__( self : str ): _a = ["DoubleLinkedList"] _a = self.head while node.next is not None: rep.append(str(__a ) ) _a = node.next rep.append(str(self.rear ) ) return ",\n ".join(__a ) def UpperCamelCase__ ( self : int , __a : DoubleLinkedListNode[T, U] ): _a = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _a = node _a = previous _a = node _a = self.rear def UpperCamelCase__ ( self : Any , __a : DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None _a = node.next _a = node.prev _a = None _a = None return node class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" __a ={} def __init__( self : Union[str, Any] , __a : int ): _a = DoubleLinkedList() _a = capacity _a = 0 _a = 0 _a = 0 _a = {} def __repr__( self : Optional[int] ): return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self : str , __a : T ): return key in self.cache def UpperCamelCase__ ( self : str , __a : T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _a = self.cache[key] _a = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__a ) return node.val self.miss += 1 return None def UpperCamelCase__ ( self : Tuple , __a : T , __a : U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _a = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _a = DoubleLinkedListNode(__a , __a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _a = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _a = value self.list.add(__a ) @classmethod def UpperCamelCase__ ( cls : Tuple , __a : int = 1_28 ): def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _a = LRUCache(__a ) _a = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _a = func(*__a ) cls.decorator_function_to_instance_map[func].put(args[0] , __a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__a , "cache_info" , __a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer lowerCAmelCase_ : Tuple = logging.get_logger(__name__) lowerCAmelCase_ : Dict = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase_ : List[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } lowerCAmelCase_ : str = { 'yjernite/retribert-base-uncased': 5_12, } lowerCAmelCase_ : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a =PRETRAINED_INIT_CONFIGURATION __a =RetriBertTokenizer __a =['input_ids', 'attention_mask'] def __init__( self : Optional[int] , __a : Optional[int]=None , __a : List[Any]=None , __a : List[Any]=True , __a : List[str]="[UNK]" , __a : Dict="[SEP]" , __a : Optional[Any]="[PAD]" , __a : Tuple="[CLS]" , __a : str="[MASK]" , __a : int=True , __a : Tuple=None , **__a : Any , ): super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) _a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , __a ) != do_lower_case or normalizer_state.get("strip_accents" , __a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , __a ) != tokenize_chinese_chars ): _a = getattr(__a , normalizer_state.pop("type" ) ) _a = do_lower_case _a = strip_accents _a = tokenize_chinese_chars _a = normalizer_class(**__a ) _a = do_lower_case def UpperCamelCase__ ( self : Any , __a : Dict , __a : Any=None ): _a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase__ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ): _a = [self.sep_token_id] _a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase__ ( self : Tuple , __a : str , __a : Optional[str] = None ): _a = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
359
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowerCamelCase ( lowercase : str ) -> str: re.sub("<n>" , "" , lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowercase ) )
346
0
'''simple docstring''' from __future__ import annotations import math def _lowerCamelCase ( lowercase : int ) -> list[int]: if num <= 0: _a = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(a__ ) _a = [True] * (num + 1) _a = [] _a = 2 _a = int(math.sqrt(a__ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(a__ ) # Set multiples of start be False for i in range(start * start , num + 1 , a__ ): if sieve[i] is True: _a = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(a__ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
360
'''simple docstring''' import requests lowerCAmelCase_ : List[Any] = 'YOUR API KEY' def _lowerCamelCase ( lowercase : str , lowercase : str = giphy_api_key ) -> list: _a = "+".join(query.split() ) _a = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' _a = requests.get(lowercase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
346
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowerCAmelCase_ : List[str] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (__lowercase ): """simple docstring""" def __init__( self : Optional[Any] , *__a : Any , **__a : Any ): warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , UpperCAmelCase__ , ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =BertGenerationTokenizer __a =False __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = BertGenerationTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ ( self : Tuple ): _a = "<s>" _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[str] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__a ) , 10_02 ) def UpperCamelCase__ ( self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def UpperCamelCase__ ( self : Tuple ): _a = BertGenerationTokenizer(__a , keep_accents=__a ) _a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [2_85, 46, 10, 1_70, 3_82] , ) _a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _a = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def UpperCamelCase__ ( self : Any ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def UpperCamelCase__ ( self : List[str] ): _a = "Hello World!" _a = [1_85_36, 22_60, 1_01] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def UpperCamelCase__ ( self : Optional[int] ): _a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def UpperCamelCase__ ( self : Tuple ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _a = list(self.big_tokenizer.get_vocab().keys() )[:10] _a = " ".join(__a ) _a = self.big_tokenizer.encode_plus(__a , return_tensors="pt" , return_token_type_ids=__a ) _a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__a ) _a = BertGenerationConfig() _a = BertGenerationEncoder(__a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def UpperCamelCase__ ( self : Optional[int] ): # fmt: off _a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
346
0
'''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 __SCREAMING_SNAKE_CASE : """simple docstring""" @staticmethod def UpperCamelCase__ ( *__a : List[Any] , **__a : List[str] ): pass @is_pipeline_test @require_vision @require_timm @require_torch class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" __a =MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCamelCase__ ( self : Any , __a : Union[str, Any] , __a : Any , __a : Tuple ): _a = ObjectDetectionPipeline(model=_a , image_processor=_a ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCamelCase__ ( self : Union[str, Any] , __a : Optional[int] , __a : Dict ): _a = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 ) self.assertGreater(len(_a ) , 0 ) for detected_object in outputs: self.assertEqual( _a , { "score": ANY(_a ), "label": ANY(_a ), "box": {"xmin": ANY(_a ), "ymin": ANY(_a ), "xmax": ANY(_a ), "ymax": ANY(_a )}, } , ) import datasets _a = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) _a = [ 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"""], ] _a = object_detector(_a , threshold=0.0 ) self.assertEqual(len(_a ) , len(_a ) ) for outputs in batch_outputs: self.assertGreater(len(_a ) , 0 ) for detected_object in outputs: self.assertEqual( _a , { "score": ANY(_a ), "label": ANY(_a ), "box": {"xmin": ANY(_a ), "ymin": ANY(_a ), "xmax": ANY(_a ), "ymax": ANY(_a )}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF" ) def UpperCamelCase__ ( self : Optional[Any] ): pass @require_torch def UpperCamelCase__ ( self : Dict ): _a = """hf-internal-testing/tiny-detr-mobilenetsv3""" _a = AutoModelForObjectDetection.from_pretrained(_a ) _a = AutoFeatureExtractor.from_pretrained(_a ) _a = ObjectDetectionPipeline(model=_a , feature_extractor=_a ) _a = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ] , ) _a = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ], [ {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 1_59, "ymin": 1_20, "xmax": 4_80, "ymax": 3_59}}, ], ] , ) @require_torch @slow def UpperCamelCase__ ( self : int ): _a = """facebook/detr-resnet-50""" _a = AutoModelForObjectDetection.from_pretrained(_a ) _a = AutoFeatureExtractor.from_pretrained(_a ) _a = ObjectDetectionPipeline(model=_a , feature_extractor=_a ) _a = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) _a = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], ] , ) @require_torch @slow def UpperCamelCase__ ( self : int ): _a = """facebook/detr-resnet-50""" _a = pipeline("object-detection" , model=_a ) _a = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) _a = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], [ {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 1_75, "ymax": 1_17}}, {"score": 0.9960, "label": "remote", "box": {"xmin": 3_33, "ymin": 72, "xmax": 3_68, "ymax": 1_87}}, {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 6_39, "ymax": 4_73}}, {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ], ] , ) @require_torch @slow def UpperCamelCase__ ( self : str ): _a = 0.9985 _a = """facebook/detr-resnet-50""" _a = pipeline("object-detection" , model=_a ) _a = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=_a ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 3_14, "ymax": 4_70}}, {"score": 0.9987, "label": "cat", "box": {"xmin": 3_45, "ymin": 23, "xmax": 6_40, "ymax": 3_68}}, ] , ) @require_torch @require_pytesseract @slow def UpperCamelCase__ ( self : Union[str, Any] ): _a = """Narsil/layoutlmv3-finetuned-funsd""" _a = 0.9993 _a = pipeline("object-detection" , model=_a , threshold=_a ) _a = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 2_94, "ymin": 2_54, "xmax": 3_43, "ymax": 2_64}}, {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 2_94, "ymin": 2_54, "xmax": 3_43, "ymax": 2_64}}, ] , )
362
'''simple docstring''' def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Union[str, Any]: _enforce_args(lowercase , lowercase ) if n == 0: return 0 _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase ) ) return max_revue def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Tuple: _enforce_args(lowercase , lowercase ) _a = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase , lowercase , lowercase ) def _lowerCamelCase ( lowercase : int , lowercase : list , lowercase : list ) -> List[str]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase , lowercase ) , ) _a = max_revenue return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Any: _enforce_args(lowercase , lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _a = [float("-inf" ) for _ in range(n + 1 )] _a = 0 for i in range(1 , n + 1 ): _a = max_rev[i] for j in range(1 , i + 1 ): _a = max(lowercase , prices[j - 1] + max_rev[i - j] ) _a = max_revenue_i return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Dict: if n < 0: _a = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): _a = ( "Each integral piece of rod must have a corresponding price. " F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def _lowerCamelCase ( ) -> Any: _a = [6, 10, 12, 15, 20, 23] _a = len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _a = 36 _a = top_down_cut_rod(lowercase , lowercase ) _a = bottom_up_cut_rod(lowercase , lowercase ) _a = naive_cut_rod_recursive(lowercase , lowercase ) 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()
346
0
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Any , __a : int = 16 , __a : int = 88 , __a : Optional[int] = None , __a : int = 1 , __a : float = 0.0 , __a : int = 32 , __a : Optional[int] = None , __a : bool = False , __a : Optional[int] = None , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , ): super().__init__() _a = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , in_channels=__SCREAMING_SNAKE_CASE , num_layers=__SCREAMING_SNAKE_CASE , dropout=__SCREAMING_SNAKE_CASE , norm_num_groups=__SCREAMING_SNAKE_CASE , cross_attention_dim=__SCREAMING_SNAKE_CASE , attention_bias=__SCREAMING_SNAKE_CASE , sample_size=__SCREAMING_SNAKE_CASE , num_vector_embeds=__SCREAMING_SNAKE_CASE , activation_fn=__SCREAMING_SNAKE_CASE , num_embeds_ada_norm=__SCREAMING_SNAKE_CASE , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference _a = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` _a = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` _a = [1, 0] def UpperCamelCase__ ( self : int , __a : List[str] , __a : int , __a : Union[str, Any]=None , __a : Any=None , __a : Optional[Any]=None , __a : bool = True , ): _a = hidden_states _a = [] _a = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens _a = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] _a = self.transformer_index_for_condition[i] _a = self.transformers[transformer_index]( __SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , timestep=__SCREAMING_SNAKE_CASE , cross_attention_kwargs=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] _a = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) _a = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__SCREAMING_SNAKE_CASE )
363
'''simple docstring''' 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_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , *__a : Optional[int] , **__a : List[str] ): super().__init__(*__a , **__a ) self.check_model_type(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : int=None , __a : Optional[Any]=None , **__a : List[Any] ): _a , _a = {}, {} if padding is not None: _a = padding if truncation is not None: _a = truncation if top_k is not None: _a = top_k return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __a : Union["Image.Image", str] , __a : str = None , **__a : Any ): if isinstance(__a , (Image.Image, str) ) and isinstance(__a , __a ): _a = {"image": image, "question": question} else: _a = image _a = super().__call__(__a , **__a ) return results def UpperCamelCase__ ( self : Tuple , __a : Tuple , __a : Optional[Any]=False , __a : List[Any]=False ): _a = load_image(inputs["image"] ) _a = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=__a , truncation=__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) model_inputs.update(__a ) return model_inputs def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.sigmoid()[0] _a , _a = probs.topk(__a ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
346
0
'''simple docstring''' from __future__ import annotations def _lowerCamelCase ( lowercase : List[str] , lowercase : str ) -> bool: _a = get_failure_array(__snake_case ) # 2) Step through text searching for pattern _a = 0, 0 # index into text, pattern while i < len(__snake_case ): if pattern[j] == text[i]: if j == (len(__snake_case ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _a = failure[j - 1] continue i += 1 return False def _lowerCamelCase ( lowercase : Dict ) -> list[int]: _a = [0] _a = 0 _a = 1 while j < len(__snake_case ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _a = failure[i - 1] continue j += 1 failure.append(__snake_case ) return failure if __name__ == "__main__": # Test 1) lowerCAmelCase_ : Tuple = 'abc1abc12' lowerCAmelCase_ : Union[str, Any] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' lowerCAmelCase_ : Dict = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) lowerCAmelCase_ : List[str] = 'ABABX' lowerCAmelCase_ : int = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) lowerCAmelCase_ : List[Any] = 'AAAB' lowerCAmelCase_ : Union[str, Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) lowerCAmelCase_ : List[str] = 'abcdabcy' lowerCAmelCase_ : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) lowerCAmelCase_ : List[str] = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
364
'''simple docstring''' from random import randint, random def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : bool = False , lowercase : int = 5 , ) -> list: _a = [[-1] * number_of_cells] # Create a highway without any car _a = 0 _a = max(lowercase , 0 ) while i < number_of_cells: _a = ( randint(0 , lowercase ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( lowercase : list , lowercase : int ) -> int: _a = 0 _a = highway_now[car_index + 1 :] for cell in range(len(lowercase ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(lowercase , -1 ) def _lowerCamelCase ( lowercase : list , lowercase : float , lowercase : int ) -> list: _a = len(lowercase ) # Beforce calculations, the highway is empty _a = [-1] * number_of_cells for car_index in range(lowercase ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _a = min(highway_now[car_index] + 1 , lowercase ) # Number of empty cell before the next car _a = get_distance(lowercase , lowercase ) - 1 # We can't have the car causing an accident _a = min(next_highway[car_index] , lowercase ) if random() < probability: # Randomly, a driver will slow down _a = max(next_highway[car_index] - 1 , 0 ) return next_highway def _lowerCamelCase ( lowercase : list , lowercase : int , lowercase : float , lowercase : int ) -> list: _a = len(highway[0] ) for i in range(lowercase ): _a = update(highway[i] , lowercase , lowercase ) _a = [-1] * number_of_cells for car_index in range(lowercase ): _a = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _a = (car_index + speed) % number_of_cells # Commit the change of position _a = speed highway.append(lowercase ) return highway if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ : Tuple = logging.get_logger(__name__) lowerCAmelCase_ : Tuple = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE (__snake_case ): """simple docstring""" __a ="distilbert" __a ={ "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self : int , __a : List[str]=3_05_22 , __a : Dict=5_12 , __a : Optional[int]=False , __a : List[str]=6 , __a : int=12 , __a : Tuple=7_68 , __a : str=4 * 7_68 , __a : List[str]=0.1 , __a : str=0.1 , __a : Dict="gelu" , __a : Optional[int]=0.02 , __a : Optional[Any]=0.1 , __a : int=0.2 , __a : Optional[Any]=0 , **__a : str , ): _a = vocab_size _a = max_position_embeddings _a = sinusoidal_pos_embds _a = n_layers _a = n_heads _a = dim _a = hidden_dim _a = dropout _a = attention_dropout _a = activation _a = initializer_range _a = qa_dropout _a = seq_classif_dropout super().__init__(**lowerCamelCase_ , pad_token_id=lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (__snake_case ): """simple docstring""" @property def UpperCamelCase__ ( self : Any ): if self.task == "multiple-choice": _a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
365
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
346
0
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase_ : Dict = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase_ : Dict = direct_transformers_import(PATH_TO_TRANSFORMERS) lowerCAmelCase_ : Any = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase_ : Dict = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)') lowerCAmelCase_ : int = { """DecisionTransformerConfig""", """EncoderDecoderConfig""", """MusicgenConfig""", """RagConfig""", """SpeechEncoderDecoderConfig""", """TimmBackboneConfig""", """VisionEncoderDecoderConfig""", """VisionTextDualEncoderConfig""", """LlamaConfig""", } def _lowerCamelCase ( lowercase : List[str] ) -> List[str]: _a = None # source code of `config_class` _a = inspect.getsource(SCREAMING_SNAKE_CASE_ ) _a = _re_checkpoint.findall(SCREAMING_SNAKE_CASE_ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("/" ): _a = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link _a = F'https://huggingface.co/{ckpt_name}' if ckpt_link == ckpt_link_from_name: _a = ckpt_name break return checkpoint def _lowerCamelCase ( ) -> int: _a = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue _a = get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE_ ) _a = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: _a = "\n".join(sorted(SCREAMING_SNAKE_CASE_ ) ) raise ValueError(F'The following configurations don\'t contain any valid checkpoint:\n{message}' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0
'''simple docstring''' from __future__ import annotations class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : int = 0 ): _a = key def UpperCamelCase__ ( self : List[str] , __a : str , __a : int ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) _a = key or self.__key or 1 # make sure key is an appropriate size key %= 2_55 return [chr(ord(_UpperCAmelCase ) ^ key ) for ch in content] def UpperCamelCase__ ( self : Union[str, Any] , __a : str , __a : int ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) _a = key or self.__key or 1 # make sure key is an appropriate size key %= 2_55 return [chr(ord(_UpperCAmelCase ) ^ key ) for ch in content] def UpperCamelCase__ ( self : Any , __a : str , __a : int = 0 ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) _a = key or self.__key or 1 # make sure key can be any size while key > 2_55: key -= 2_55 # This will be returned _a = "" for ch in content: ans += chr(ord(_UpperCAmelCase ) ^ key ) return ans def UpperCamelCase__ ( self : Union[str, Any] , __a : str , __a : int = 0 ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) _a = key or self.__key or 1 # make sure key can be any size while key > 2_55: key -= 2_55 # This will be returned _a = "" for ch in content: ans += chr(ord(_UpperCAmelCase ) ^ key ) return ans def UpperCamelCase__ ( self : Any , __a : str , __a : int = 0 ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) try: with open(_UpperCAmelCase ) as fin, open("encrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(_UpperCAmelCase , _UpperCAmelCase ) ) except OSError: return False return True def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and isinstance(_UpperCAmelCase , _UpperCAmelCase ) try: with open(_UpperCAmelCase ) as fin, open("decrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(_UpperCAmelCase , _UpperCAmelCase ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
367
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ : List[Any] = logging.getLogger(__name__) lowerCAmelCase_ : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowerCAmelCase_ : int = {'facebook/bart-base': BartTokenizer} def _lowerCamelCase ( ) -> Union[str, Any]: _a = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=lowercase , default=lowercase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=lowercase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowercase , default=lowercase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowercase , ) parser.add_argument( "--config_name" , type=lowercase , default=lowercase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowercase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowercase , default=lowercase , help="Where to store the final ONNX file." ) _a = parser.parse_args() return args def _lowerCamelCase ( lowercase : Any , lowercase : Tuple="cpu" ) -> Optional[Any]: _a = model_dict[model_name].from_pretrained(lowercase ).to(lowercase ) _a = tokenizer_dict[model_name].from_pretrained(lowercase ) if model_name in ["facebook/bart-base"]: _a = 0 _a = None _a = 0 return huggingface_model, tokenizer def _lowerCamelCase ( lowercase : List[str] , lowercase : Tuple , lowercase : int , lowercase : Any , lowercase : Dict ) -> Any: model.eval() _a = None _a = torch.jit.script(BARTBeamSearchGenerator(lowercase ) ) with torch.no_grad(): _a = "My friends are cool but they eat too many carbs." _a = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) _a = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowercase , max_length=lowercase , early_stopping=lowercase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowercase , ) logger.info("Model exported to {}".format(lowercase ) ) _a = remove_dup_initializers(os.path.abspath(lowercase ) ) logger.info("Deduplicated and optimized model written to {}".format(lowercase ) ) _a = onnxruntime.InferenceSession(lowercase ) _a = ort_sess.run( lowercase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowercase ), "max_length": np.array(lowercase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def _lowerCamelCase ( ) -> Any: _a = parse_args() _a = 5 _a = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _a = torch.device(args.device ) _a , _a = load_model_tokenizer(args.model_name_or_path , lowercase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(lowercase ) if args.max_length: _a = args.max_length if args.num_beams: _a = args.num_beams if args.output_file_path: _a = args.output_file_path else: _a = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(lowercase , lowercase , lowercase , lowercase , lowercase ) if __name__ == "__main__": main()
346
0
def _lowerCamelCase ( lowercase : float , lowercase : int ) -> float: if digit_amount > 0: return round(number - int(lowercase ) , lowercase ) return number - int(lowercase ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
368
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCAmelCase_ : Dict = abspath(join(dirname(dirname(dirname(__file__))), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _lowerCamelCase ( lowercase : str ) -> Optional[int]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase ) def _lowerCamelCase ( lowercase : Dict ) -> str: from transformers.testing_utils import pytest_terminal_summary_main _a = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(lowercase , id=lowercase )
346
0
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowerCAmelCase_ : Dict = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex lowerCAmelCase_ : Tuple = 10 lowerCAmelCase_ : Union[str, Any] = 2_56 def _lowerCamelCase ( lowercase : str ) -> Optional[MinHash]: if len(a__ ) < MIN_NUM_TOKENS: return None _a = MinHash(num_perm=a__ ) for token in set(a__ ): min_hash.update(token.encode() ) return min_hash def _lowerCamelCase ( lowercase : List[Any] ) -> Set[str]: return {t for t in NON_ALPHA.split(a__ ) if len(t.strip() ) > 0} class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Optional[int] , *, __a : float = 0.85 , ): _a = duplication_jaccard_threshold _a = NUM_PERM _a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _a = defaultdict(lowercase_ ) def UpperCamelCase__ ( self : List[str] , __a : Tuple , __a : MinHash ): _a = self._index.query(lowercase_ ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(lowercase_ ) break else: self._duplicate_clusters[close_duplicates[0]].add(lowercase_ ) def UpperCamelCase__ ( self : List[str] ): _a = [] for base, duplicates in self._duplicate_clusters.items(): _a = [base] + list(lowercase_ ) # reformat the cluster to be a list of dict _a = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(lowercase_ ) return duplicate_clusters def UpperCamelCase__ ( self : int , __a : Optional[int] ): _a = self.get_duplicate_clusters() with open(lowercase_ , "w" ) as f: json.dump(lowercase_ , lowercase_ ) def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a , _a = element _a = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _lowerCamelCase ( lowercase : Tuple ) -> Optional[int]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a__ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def _lowerCamelCase ( lowercase : str , lowercase : Any ) -> List[str]: _a = DuplicationIndex(duplication_jaccard_threshold=a__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a__ ) ) , max_queue_size=100 ) ): di.add(a__ , a__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _lowerCamelCase ( lowercase : List[Any] , lowercase : Union[str, Any] ) -> float: _a = get_tokens(a__ ) _a = get_tokens(a__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( lowercase : Dict , lowercase : int ) -> Optional[Any]: _a = [] for elementa in cluster: _a = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: _a = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(a__ , a__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: _a = 1 extremes.append(a__ ) return extremes def _lowerCamelCase ( lowercase : List[Any] , lowercase : Optional[Any] , lowercase : Any ) -> str: global _shared_dataset _a = dataset _a = [] _a = partial(_find_cluster_extremes_shared , jaccard_threshold=a__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a__ , a__ , ) , total=len(a__ ) , ): extremes_list.append(a__ ) return extremes_list def _lowerCamelCase ( lowercase : Tuple , lowercase : Union[str, Any] = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _a = make_duplicate_clusters(a__ , a__ ) _a = {x["base_index"] for cluster in duplicate_clusters for x in cluster} _a = {} _a = find_extremes(a__ , a__ , a__ ) for extremes in extremes_clusters: for element in extremes: _a = element _a = duplicate_indices - set(extreme_dict.keys() ) _a = dataset.filter(lambda lowercase , lowercase : idx not in remove_indices , with_indices=a__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _a = element["base_index"] in extreme_dict if element["is_extreme"]: _a = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(a__ )}' ) print(F'Number of duplicate clusters: {len(a__ )}' ) print(F'Files in duplicate cluster: {len(a__ )}' ) print(F'Unique files in duplicate cluster: {len(a__ )}' ) print(F'Filtered dataset size: {len(a__ )}' ) return ds_filter, duplicate_clusters
369
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @register_to_config def __init__( self : List[Any] , __a : int , __a : int , __a : int , __a : float , __a : int , __a : int , __a : int , __a : int , __a : str , __a : bool = False , ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.Embedding(__a , __a ) _a = False _a = nn.Dropout(p=__a ) _a = TaConfig( vocab_size=__a , d_model=__a , num_heads=__a , d_kv=__a , d_ff=__a , dropout_rate=__a , feed_forward_proj=__a , is_decoder=__a , is_encoder_decoder=__a , ) _a = nn.ModuleList() for lyr_num in range(__a ): _a = TaBlock(__a ) self.encoders.append(__a ) _a = TaLayerNorm(__a ) _a = nn.Dropout(p=__a ) def UpperCamelCase__ ( self : str , __a : Union[str, Any] , __a : Dict ): _a = self.token_embedder(__a ) _a = encoder_input_tokens.shape[1] _a = torch.arange(__a , device=encoder_input_tokens.device ) x += self.position_encoding(__a ) _a = self.dropout_pre(__a ) # inverted the attention mask _a = encoder_input_tokens.size() _a = self.get_extended_attention_mask(__a , __a ) for lyr in self.encoders: _a = lyr(__a , __a )[0] _a = self.layer_norm(__a ) return self.dropout_post(__a ), encoder_inputs_mask
346
0
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = torch.exp(_lowerCamelCase ) _a = torch.sum(_lowerCamelCase , dim=1 ) # sum of exp(x_i) _a = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(_lowerCamelCase ) - B / A class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[str] , __a : str ): super().__init__() _a = config.output_attentions _a = config.output_hidden_states _a = nn.ModuleList([BertLayer(__a ) for _ in range(config.num_hidden_layers )] ) _a = nn.ModuleList([BertHighway(__a ) for _ in range(config.num_hidden_layers )] ) _a = [-1 for _ in range(config.num_hidden_layers )] def UpperCamelCase__ ( self : str , __a : int ): if (type(__a ) is float) or (type(__a ) is int): for i in range(len(self.early_exit_entropy ) ): _a = x else: _a = x def UpperCamelCase__ ( self : Optional[int] , __a : Union[str, Any] ): _a = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def UpperCamelCase__ ( self : int , __a : Any , __a : Any=None , __a : Union[str, Any]=None , __a : str=None , __a : str=None , ): _a = () _a = () _a = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: _a = all_hidden_states + (hidden_states,) _a = layer_module( __a , __a , head_mask[i] , __a , __a ) _a = layer_outputs[0] if self.output_attentions: _a = all_attentions + (layer_outputs[1],) _a = (hidden_states,) if self.output_hidden_states: _a = current_outputs + (all_hidden_states,) if self.output_attentions: _a = current_outputs + (all_attentions,) _a = self.highway[i](__a ) # logits, pooled_output if not self.training: _a = highway_exit[0] _a = entropy(__a ) _a = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy _a = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: _a = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(__a , i + 1 ) else: _a = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: _a = all_hidden_states + (hidden_states,) _a = (hidden_states,) if self.output_hidden_states: _a = outputs + (all_hidden_states,) if self.output_attentions: _a = outputs + (all_attentions,) _a = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( 'The Bert Model transformer with early exiting (DeeBERT). ' , a__ , ) class __SCREAMING_SNAKE_CASE (a__ ): """simple docstring""" def __init__( self : int , __a : Dict ): super().__init__(__a ) _a = config _a = BertEmbeddings(__a ) _a = DeeBertEncoder(__a ) _a = BertPooler(__a ) self.init_weights() def UpperCamelCase__ ( self : Optional[Any] ): self.encoder.init_highway_pooler(self.pooler ) def UpperCamelCase__ ( self : List[str] ): return self.embeddings.word_embeddings def UpperCamelCase__ ( self : Dict , __a : Tuple ): _a = value def UpperCamelCase__ ( self : Union[str, Any] , __a : Any ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(__a ) @add_start_docstrings_to_model_forward(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Any=None , __a : Union[str, Any]=None , __a : Optional[Any]=None , __a : List[str]=None , __a : List[str]=None , __a : List[str]=None , __a : Any=None , __a : Union[str, Any]=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: _a = input_ids.size() elif inputs_embeds is not None: _a = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds" ) _a = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _a = torch.ones(__a , device=__a ) if encoder_attention_mask is None: _a = torch.ones(__a , device=__a ) if token_type_ids is None: _a = torch.zeros(__a , dtype=torch.long , device=__a ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _a = self.get_extended_attention_mask(__a , __a , __a ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: _a = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: _a = encoder_attention_mask[:, None, None, :] _a = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility _a = (1.0 - encoder_extended_attention_mask) * -1_00_00.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _a = self.get_head_mask(__a , self.config.num_hidden_layers ) _a = self.embeddings( input_ids=__a , position_ids=__a , token_type_ids=__a , inputs_embeds=__a ) _a = self.encoder( __a , attention_mask=__a , head_mask=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , ) _a = encoder_outputs[0] _a = self.pooler(__a ) _a = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __SCREAMING_SNAKE_CASE (a__ ): """simple docstring""" def __init__( self : Optional[Any] , __a : str , __a : List[str] ): _a = message _a = exit_layer # start from 1! class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : int ): super().__init__() _a = BertPooler(__a ) _a = nn.Dropout(config.hidden_dropout_prob ) _a = nn.Linear(config.hidden_size , config.num_labels ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): # Pooler _a = encoder_outputs[0] _a = self.pooler(__a ) # "return" pooler_output # BertModel _a = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification _a = bmodel_output[1] _a = self.dropout(__a ) _a = self.classifier(__a ) return logits, pooled_output @add_start_docstrings( 'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ' , a__ , ) class __SCREAMING_SNAKE_CASE (a__ ): """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] ): super().__init__(__a ) _a = config.num_labels _a = config.num_hidden_layers _a = DeeBertModel(__a ) _a = nn.Dropout(config.hidden_dropout_prob ) _a = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(__a ) def UpperCamelCase__ ( self : List[str] , __a : int=None , __a : Union[str, Any]=None , __a : Any=None , __a : Optional[Any]=None , __a : List[str]=None , __a : Any=None , __a : Optional[int]=None , __a : int=-1 , __a : Optional[int]=False , ): _a = self.num_layers try: _a = self.bert( __a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits _a = outputs[1] _a = self.dropout(__a ) _a = self.classifier(__a ) _a = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _a = e.message _a = e.exit_layer _a = outputs[0] if not self.training: _a = entropy(__a ) _a = [] _a = [] if labels is not None: if self.num_labels == 1: # We are doing regression _a = MSELoss() _a = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _a = CrossEntropyLoss() _a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _a = [] for highway_exit in outputs[-1]: _a = highway_exit[0] if not self.training: highway_logits_all.append(__a ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _a = MSELoss() _a = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _a = CrossEntropyLoss() _a = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__a ) if train_highway: _a = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _a = (loss,) + outputs if not self.training: _a = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _a = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
370
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Any: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : List[str] = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Union[str, Any]: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": _a = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Dict , lowercase : Dict ) -> str: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Tuple , __a : Optional[int] , __a : Any ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Tuple , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Dict=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : List[Any] , __a : Dict ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Union[str, Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Optional[int] , __a : pl.Trainer , __a : str ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
346
0
'''simple docstring''' from numpy import exp, pi, sqrt def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[int] = 0.0 , lowercase : Any = 1.0 ) -> List[str]: return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
371
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): lowerCAmelCase_ : str = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ : Union[str, Any] = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = (images / 2 + 0.5).clamp(0 , 1 ) _a = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _a = numpy_to_pil(lowercase ) return images def _lowerCamelCase ( lowercase : int ) -> List[Any]: if images.ndim == 3: _a = images[None, ...] _a = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _a = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: _a = [Image.fromarray(lowercase ) for image in images] return pil_images
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase_ : Union[str, Any] = {"tokenization_byt5": ["ByT5Tokenizer"]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys lowerCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
350
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: _a = 10 _a = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) _a = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(lowercase ) ), } , features=lowercase , ) return dataset @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=lowercase ) return filename # FILE_CONTENT + files lowerCAmelCase_ : Union[str, Any] = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = tmp_path_factory.mktemp("data" ) / "file.txt" _a = FILE_CONTENT with open(lowercase , "w" ) as f: f.write(lowercase ) return filename @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: import bza _a = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" _a = bytes(lowercase , "utf-8" ) with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Optional[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) _a = bytes(lowercase , "utf-8" ) with gzip.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Union[str, Any]: if datasets.config.LZ4_AVAILABLE: import lza.frame _a = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" _a = bytes(lowercase , "utf-8" ) with lza.frame.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Tuple ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _a = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(lowercase , "w" ) as archive: archive.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[Any] ) -> Dict: import tarfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any ) -> Union[str, Any]: import lzma _a = tmp_path_factory.mktemp("data" ) / "file.txt.xz" _a = bytes(lowercase , "utf-8" ) with lzma.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int , lowercase : Any ) -> Union[str, Any]: import zipfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> List[str]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _a = tmp_path_factory.mktemp("data" ) / "file.txt.zst" _a = bytes(lowercase , "utf-8" ) with zstd.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "file.xml" _a = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(lowercase , "w" ) as f: f.write(lowercase ) return filename lowerCAmelCase_ : Optional[int] = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] lowerCAmelCase_ : Dict = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } lowerCAmelCase_ : Dict = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> str: _a = datasets.Dataset.from_dict(lowercase ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> Dict: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(lowercase ) ) as con: _a = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> int: import bza _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(lowercase , "rb" ) as f: _a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Any , lowercase : Any ) -> List[str]: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Any , lowercase : List[Any] ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(lowercase , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Optional[Any] , lowercase : int ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) _a = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(lowercase , "wb" ) as f: _a = pq.ParquetWriter(lowercase , schema=lowercase ) _a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase ) )] for k in DATA[0]} , schema=lowercase ) writer.write_table(lowercase ) writer.close() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA_DICT_OF_LISTS} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> List[str]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_312: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> int: _a = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_STR: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Tuple: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : List[Any] ) -> List[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[Any] , lowercase : int ) -> str: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : int , lowercase : List[Any] ) -> Optional[int]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] , lowercase : str ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : Any , lowercase : Optional[int] ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str , lowercase : List[str] , lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> str: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Dict: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Dict: _a = ["0", "1", "2", "3"] _a = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Union[str, Any] , lowercase : Any ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : List[str] , lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int , lowercase : str ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename("unsupported.ext" ) ) f.write(lowercase , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Any: _a = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(lowercase , "w" , encoding="utf-8" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[Any]: return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: _a = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int ) -> bool: return str(_SCREAMING_SNAKE_CASE ) == str(_SCREAMING_SNAKE_CASE )[::-1] def _lowerCamelCase ( lowercase : int ) -> int: return int(_SCREAMING_SNAKE_CASE ) + int(str(_SCREAMING_SNAKE_CASE )[::-1] ) def _lowerCamelCase ( lowercase : int = 1_0000 ) -> int: _a = [] for num in range(1 , _SCREAMING_SNAKE_CASE ): _a = 0 _a = num while iterations < 50: _a = sum_reverse(_SCREAMING_SNAKE_CASE ) iterations += 1 if is_palindrome(_SCREAMING_SNAKE_CASE ): break else: lychrel_nums.append(_SCREAMING_SNAKE_CASE ) return len(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(f"""{solution() = }""")
351
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='LayoutLMv2ImageProcessor' __a =('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Dict , __a : int=None , __a : List[Any]=None , **__a : str ): if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self : Optional[int] , __a : Optional[Any] , __a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __a : Union[List[List[int]], List[List[List[int]]]] = None , __a : Optional[Union[List[int], List[List[int]]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = None , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Optional[Any] , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor _a = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): _a = [text] # add batch dimension (as the image processor always adds a batch dimension) _a = features["words"] _a = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values _a = features.pop("pixel_values" ) if return_overflowing_tokens is True: _a = self.get_overflowing_images(__a , encoded_inputs["overflow_to_sample_mapping"] ) _a = images return encoded_inputs def UpperCamelCase__ ( self : int , __a : List[Any] , __a : int ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(__a )} and {len(__a )}' ) return images_with_overflow def UpperCamelCase__ ( self : Optional[Any] , *__a : Dict , **__a : Union[str, Any] ): return self.tokenizer.batch_decode(*__a , **__a ) def UpperCamelCase__ ( self : Union[str, Any] , *__a : Optional[int] , **__a : Optional[Any] ): return self.tokenizer.decode(*__a , **__a ) @property def UpperCamelCase__ ( self : int ): return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase__ ( self : List[Any] ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , ) return self.image_processor_class @property def UpperCamelCase__ ( self : int ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , ) return self.image_processor
346
0
'''simple docstring''' import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : Union[str, Any] , __a : Union[str, Any]=13 , __a : Tuple=7 , __a : List[str]=True , __a : int=True , __a : Optional[int]=False , __a : str=True , __a : List[Any]=99 , __a : Tuple=64 , __a : List[str]=5 , __a : Optional[int]=4 , __a : Optional[Any]=64 , __a : int="gelu" , __a : Union[str, Any]=0.1 , __a : Union[str, Any]=0.1 , __a : str=5_12 , __a : Dict=16 , __a : str=2 , __a : Any=0.02 , __a : Any=3 , __a : Optional[int]=4 , __a : Dict=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope def UpperCamelCase__ ( self : List[str] ): return MPNetConfig.from_pretrained("microsoft/mpnet-base" ) def UpperCamelCase__ ( self : int ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self : int ): return MPNetConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCamelCase__ ( self : Dict , __a : Union[str, Any] , __a : Dict , __a : Union[str, Any] , __a : Tuple , __a : Dict , __a : Dict ): _a = MPNetModel(config=__a ) model.to(__a ) model.eval() _a = model(__a , __a ) _a = model(__a ) 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 UpperCamelCase__ ( self : int , __a : Union[str, Any] , __a : str , __a : Tuple , __a : Tuple , __a : Union[str, Any] , __a : int ): _a = MPNetForQuestionAnswering(config=__a ) model.to(__a ) model.eval() _a = model( __a , attention_mask=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : Optional[Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : Optional[Any] ): _a = self.num_labels _a = MPNetForSequenceClassification(__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self : Optional[Any] , __a : List[str] , __a : Optional[int] , __a : Dict , __a : Optional[Any] , __a : Optional[Any] , __a : List[str] ): _a = self.num_choices _a = MPNetForMultipleChoice(config=__a ) model.to(__a ) model.eval() _a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = model( __a , attention_mask=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self : Optional[int] , __a : Optional[int] , __a : Dict , __a : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): _a = self.num_labels _a = MPNetForTokenClassification(config=__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : List[Any] ): _a = self.prepare_config_and_inputs() (_a) = config_and_inputs _a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) __a =( { 'feature-extraction': MPNetModel, 'fill-mask': MPNetForMaskedLM, 'question-answering': MPNetForQuestionAnswering, 'text-classification': MPNetForSequenceClassification, 'token-classification': MPNetForTokenClassification, 'zero-shot': MPNetForSequenceClassification, } if is_torch_available() else {} ) __a =False __a =True def UpperCamelCase__ ( self : List[str] ): _a = MPNetModelTester(self ) _a = ConfigTester(self , config_class=__a , hidden_size=37 ) def UpperCamelCase__ ( self : Union[str, Any] ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*__a ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*__a ) def UpperCamelCase__ ( self : Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*__a ) def UpperCamelCase__ ( self : int ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*__a ) @require_torch class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : int ): _a = MPNetModel.from_pretrained("microsoft/mpnet-base" ) _a = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) _a = model(__a )[0] _a = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , __a ) _a = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) )
352
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : int = '▁' lowerCAmelCase_ : Optional[Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : Union[str, Any] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['input_ids', 'attention_mask'] __a =[] def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Any="<s>" , __a : List[str]="</s>" , __a : str="<pad>" , __a : List[str]="<unk>" , __a : Union[str, Any]=False , __a : Any=False , __a : List[str]=None , __a : Optional[int]=None , __a : Optional[Dict[str, Any]] = None , **__a : int , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = do_upper_case _a = do_lower_case _a = load_json(__a ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__a , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : str ): return len(self.encoder ) @property def UpperCamelCase__ ( self : str ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : Optional[int] , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : Dict , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : List[str] , __a : Any ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a , self.unk_token ) def UpperCamelCase__ ( self : str , __a : List[str] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__a ) _a = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : int , __a : Any , __a : int=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase__ ( self : Any , __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 ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): _a = Path(__a ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(lowercase , "r" ) as f: return json.load(lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> None: with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase , indent=2 )
346
0
'''simple docstring''' import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class __SCREAMING_SNAKE_CASE (_lowerCamelCase ): """simple docstring""" __a ='facebook/bart-large-mnli' __a =( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) __a ='text_classifier' __a =AutoTokenizer __a =AutoModelForSequenceClassification __a =['text', ['text']] __a =['text'] def UpperCamelCase__ ( self : Tuple ): super().setup() _a = self.model.config _a = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): _a = int(__a ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def UpperCamelCase__ ( self : str , __a : Optional[int] , __a : str ): _a = labels return self.pre_processor( [text] * len(__a ) , [f'This example is {label}' for label in labels] , return_tensors="pt" , padding="max_length" , ) def UpperCamelCase__ ( self : int , __a : Dict ): _a = outputs.logits _a = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
353
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): _a = Rectangle(height=0.5 , width=0.5 ) _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _a = [mem.copy() for i in range(6 )] _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(__a , __a ).arrange(__a , buff=0 ) _a = Text("CPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__a ) _a = [mem.copy() for i in range(4 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("GPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) gpu.move_to([-1, -1, 0] ) self.add(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Model" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) model.move_to([3, -1.0, 0] ) self.add(__a ) _a = [] for i, rect in enumerate(__a ): rect.set_stroke(__a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__a , buff=0.0 ) self.add(__a ) cpu_targs.append(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Loaded Checkpoint" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , aligned_edge=__a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) _a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _a = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__a , __a ) _a = MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) _a = MarkupText( f'Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__a ) , Write(__a ) ) self.play(Write(__a , run_time=1 ) , Create(__a , run_time=1 ) ) _a = [] _a = [] for i, rect in enumerate(__a ): _a = fill.copy().set_fill(__a , opacity=0.7 ) target.move_to(__a ) first_animations.append(GrowFromCenter(__a , run_time=1 ) ) _a = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__a , run_time=1.5 ) ) self.play(*__a ) self.play(*__a ) self.wait()
346
0
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __SCREAMING_SNAKE_CASE (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" __a =LEDTokenizer __a =LEDTokenizerFast __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] _a = dict(zip(__a , range(len(__a ) ) ) ) _a = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] _a = {"unk_token": "<unk>"} _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__a ) ) def UpperCamelCase__ ( self : Dict , **__a : Optional[Any] ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Tuple , **__a : int ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Optional[int] , __a : Optional[Any] ): return "lower newer", "lower newer" @cached_property def UpperCamelCase__ ( self : List[Any] ): return LEDTokenizer.from_pretrained("allenai/led-base-16384" ) @cached_property def UpperCamelCase__ ( self : int ): return LEDTokenizerFast.from_pretrained("allenai/led-base-16384" ) @require_torch def UpperCamelCase__ ( self : Tuple ): _a = ["A long paragraph for summarization.", "Another paragraph for summarization."] _a = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = tokenizer(__a , max_length=len(__a ) , padding=__a , return_tensors="pt" ) self.assertIsInstance(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) _a = batch.input_ids.tolist()[0] self.assertListEqual(__a , __a ) @require_torch def UpperCamelCase__ ( self : Union[str, Any] ): _a = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = tokenizer(__a , padding=__a , return_tensors="pt" ) self.assertIn("input_ids" , __a ) self.assertIn("attention_mask" , __a ) self.assertNotIn("labels" , __a ) self.assertNotIn("decoder_attention_mask" , __a ) @require_torch def UpperCamelCase__ ( self : Union[str, Any] ): _a = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = tokenizer(text_target=__a , max_length=32 , padding="max_length" , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) @require_torch def UpperCamelCase__ ( self : Tuple ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = tokenizer( ["I am a small frog" * 10_24, "I am a small frog"] , padding=__a , truncation=__a , return_tensors="pt" ) self.assertIsInstance(__a , __a ) self.assertEqual(batch.input_ids.shape , (2, 51_22) ) @require_torch def UpperCamelCase__ ( self : Any ): _a = ["A long paragraph for summarization."] _a = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = tokenizer(__a , return_tensors="pt" ) _a = tokenizer(text_target=__a , return_tensors="pt" ) _a = inputs["input_ids"] _a = targets["input_ids"] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def UpperCamelCase__ ( self : Dict ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _a = ["Summary of the text.", "Another summary."] _a = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] _a = tokenizer(__a , padding=__a ) _a = [[0] * len(__a ) for x in encoded_output["input_ids"]] _a = tokenizer.pad(__a ) self.assertSequenceEqual(outputs["global_attention_mask"] , __a ) def UpperCamelCase__ ( self : List[str] ): pass def UpperCamelCase__ ( self : Optional[Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): _a = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _a = self.tokenizer_class.from_pretrained(__a , **__a ) _a = "A, <mask> AllenNLP sentence." _a = tokenizer_r.encode_plus(__a , add_special_tokens=__a , return_token_type_ids=__a ) _a = tokenizer_p.encode_plus(__a , add_special_tokens=__a , return_token_type_ids=__a ) self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) _a = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) _a = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) self.assertSequenceEqual(tokens_p["input_ids"] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( __a , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( __a , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
354
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase_ : Tuple = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = test_results.split(" " ) _a = 0 _a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _a = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = {} _a = None _a = False for line in failures_short_lines.split("\n" ): if re.search(r"_ \[doctest\]" , lowercase ): _a = True _a = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): _a = line _a = False return failures class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : str , __a : Dict ): _a = title _a = doc_test_results["time_spent"].split("," )[0] _a = doc_test_results["success"] _a = doc_test_results["failures"] _a = self.n_success + self.n_failures # Failures and success of the modeling tests _a = doc_test_results @property def UpperCamelCase__ ( self : int ): _a = [self._time_spent] _a = 0 for time in time_spent: _a = time.split(":" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__a ) == 1: _a = [0, 0, time_parts[0]] _a , _a , _a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds _a , _a , _a = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(__a )}h{int(__a )}m{int(__a )}s' @property def UpperCamelCase__ ( self : Optional[Any] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self : Optional[Any] ): return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : List[str] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : str ): _a = 40 _a = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__a , __a )} _a = "" for category, failures in category_failures.items(): if len(__a ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def UpperCamelCase__ ( self : List[str] ): _a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__a ) @staticmethod def UpperCamelCase__ ( ): _a = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(__a )} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=__a , ) def UpperCamelCase__ ( self : Tuple ): print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(self.payload )} ) ) _a = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else "All tests passed." _a = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=__a , ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : List[Any] , __a : Tuple , __a : int ): _a = "" for key, value in failures.items(): _a = value[:2_00] + " [Truncated]" if len(__a ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' _a = job_name _a = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: _a = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self : str ): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made." ) _a = self.doc_test_results.pop("job_link" ) self.doc_test_results.pop("failures" ) self.doc_test_results.pop("success" ) self.doc_test_results.pop("time_spent" ) _a = sorted(self.doc_test_results.items() , key=lambda __a : t[0] ) for job, job_result in sorted_dict: if len(job_result["failures"] ): _a = f'*Num failures* :{len(job_result["failed"] )} \n' _a = job_result["failures"] _a = self.get_reply_blocks(__a , __a , __a , text=__a ) print("Sending the following reply" ) print(json.dumps({"blocks": blocks} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=f'Results for {job}' , blocks=__a , thread_ts=self.thread_ts["ts"] , ) time.sleep(1 ) def _lowerCamelCase ( ) -> Any: _a = os.environ["GITHUB_RUN_ID"] _a = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _a = requests.get(lowercase ).json() _a = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) _a = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): _a = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , lowercase ) return {} def _lowerCamelCase ( lowercase : str ) -> Dict: _a = {} if os.path.exists(lowercase ): _a = os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase , lowercase ) , encoding="utf-8" ) as f: _a = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase , lowercase )}.' ) from e return _artifact def _lowerCamelCase ( ) -> str: class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str ): _a = name _a = [] def __str__( self : List[str] ): return self.name def UpperCamelCase__ ( self : str , __a : str ): self.paths.append({"name": self.name, "path": path} ) _a = {} _a = filter(os.path.isdir , os.listdir() ) for directory in directories: _a = directory if artifact_name not in _available_artifacts: _a = Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase_ : List[Any] = get_job_links() lowerCAmelCase_ : Any = retrieve_available_artifacts() lowerCAmelCase_ : List[str] = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase_ : Optional[Any] = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase_ : int = github_actions_job_links.get('run_doctests') lowerCAmelCase_ : Union[str, Any] = available_artifacts['doc_tests_gpu_test_reports'].paths[0] lowerCAmelCase_ : List[str] = retrieve_artifact(artifact_path['name']) if "stats" in artifact: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = handle_test_results(artifact['stats']) lowerCAmelCase_ : List[str] = failed lowerCAmelCase_ : Optional[Any] = success lowerCAmelCase_ : Tuple = time_spent[1:-1] + ', ' lowerCAmelCase_ : List[Any] = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): lowerCAmelCase_ : int = line.replace('FAILED ', '') lowerCAmelCase_ : Optional[int] = line.split()[0].replace('\n', '') if "::" in line: lowerCAmelCase_ , lowerCAmelCase_ : str = line.split('::') else: lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase_ : Union[str, Any] = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase_ : List[str] = all_failures[test] if test in all_failures else 'N/A' lowerCAmelCase_ : Optional[Any] = failure break lowerCAmelCase_ : Tuple = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
346
0
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='char' __a ='bpe' __a ='wp' lowerCAmelCase_ : List[str] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'char_tokenizer'] __a ='ViTImageProcessor' __a ='MgpstrTokenizer' def __init__( self : Tuple , __a : int=None , __a : Dict=None , **__a : int ): _a = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , lowerCamelCase_ , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) _a = tokenizer _a = AutoTokenizer.from_pretrained("gpt2" ) _a = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(lowerCamelCase_ , lowerCamelCase_ ) def __call__( self : int , __a : Optional[Any]=None , __a : str=None , __a : str=None , **__a : Dict ): if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: _a = self.image_processor(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if text is not None: _a = self.char_tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if text is None: return inputs elif images is None: return encodings else: _a = encodings["input_ids"] return inputs def UpperCamelCase__ ( self : Dict , __a : Union[str, Any] ): _a , _a , _a = sequences _a = char_preds.size(0 ) _a , _a = self._decode_helper(lowerCamelCase_ , "char" ) _a , _a = self._decode_helper(lowerCamelCase_ , "bpe" ) _a , _a = self._decode_helper(lowerCamelCase_ , "wp" ) _a = [] _a = [] for i in range(lowerCamelCase_ ): _a = [char_scores[i], bpe_scores[i], wp_scores[i]] _a = [char_strs[i], bpe_strs[i], wp_strs[i]] _a = scores.index(max(lowerCamelCase_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) _a = {} _a = final_strs _a = final_scores _a = char_strs _a = bpe_strs _a = wp_strs return out def UpperCamelCase__ ( self : Optional[int] , __a : Any , __a : Dict ): if format == DecodeType.CHARACTER: _a = self.char_decode _a = 1 _a = "[s]" elif format == DecodeType.BPE: _a = self.bpe_decode _a = 2 _a = "#" elif format == DecodeType.WORDPIECE: _a = self.wp_decode _a = 1_02 _a = "[SEP]" else: raise ValueError(f'Format {format} is not supported.' ) _a , _a = [], [] _a = pred_logits.size(0 ) _a = pred_logits.size(1 ) _a , _a = pred_logits.topk(1 , dim=-1 , largest=lowerCamelCase_ , sorted=lowerCamelCase_ ) _a = preds_index.view(-1 , lowerCamelCase_ )[:, 1:] _a = decoder(lowerCamelCase_ ) _a , _a = torch.nn.functional.softmax(lowerCamelCase_ , dim=2 ).max(dim=2 ) _a = preds_max_prob[:, 1:] for index in range(lowerCamelCase_ ): _a = preds_str[index].find(lowerCamelCase_ ) _a = preds_str[index][:pred_eos] _a = preds_index[index].cpu().tolist() _a = pred_index.index(lowerCamelCase_ ) if eos_token in pred_index else -1 _a = preds_max_prob[index][: pred_eos_index + 1] _a = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(lowerCamelCase_ ) conf_scores.append(lowerCamelCase_ ) return dec_strs, conf_scores def UpperCamelCase__ ( self : List[Any] , __a : List[Any] ): _a = [seq.replace(" " , "" ) for seq in self.char_tokenizer.batch_decode(lowerCamelCase_ )] return decode_strs def UpperCamelCase__ ( self : Optional[int] , __a : List[Any] ): return self.bpe_tokenizer.batch_decode(lowerCamelCase_ ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Tuple ): _a = [seq.replace(" " , "" ) for seq in self.wp_tokenizer.batch_decode(lowerCamelCase_ )] return decode_strs
355
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCamelCase ( ) -> str: _a = HfArgumentParser(lowercase ) _a = parser.parse_args_into_dataclasses()[0] _a = TensorFlowBenchmark(args=lowercase ) try: _a = parser.parse_args_into_dataclasses()[0] except ValueError as e: _a = "Arg --no_{0} is no longer used, please use --no-{0} instead." _a = " ".join(str(lowercase ).split(" " )[:-1] ) _a = "" _a = eval(str(lowercase ).split(" " )[-1] ) _a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowercase ) if len(lowercase ) > 0: _a = full_error_msg + begin_error_msg + str(lowercase ) raise ValueError(lowercase ) benchmark.run() if __name__ == "__main__": main()
346
0
'''simple docstring''' from __future__ import annotations import math def _lowerCamelCase ( lowercase : Tuple , lowercase : Optional[int] ) -> float: _a = u for i in range(1 , __UpperCAmelCase ): _a = temp * (u - i) return temp def _lowerCamelCase ( ) -> None: _a = int(input("enter the numbers of values: " ) ) _a = [] for _ in range(__UpperCAmelCase ): y.append([] ) for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): y[i].append(__UpperCAmelCase ) _a = 0 print("enter the values of parameters in a list: " ) _a = list(map(__UpperCAmelCase , input().split() ) ) print("enter the values of corresponding parameters: " ) for i in range(__UpperCAmelCase ): _a = float(input() ) _a = int(input("enter the value to interpolate: " ) ) _a = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , __UpperCAmelCase ): for j in range(n - i ): _a = y[j + 1][i - 1] - y[j][i - 1] _a = y[0][0] for i in range(1 , __UpperCAmelCase ): summ += (ucal(__UpperCAmelCase , __UpperCAmelCase ) * y[0][i]) / math.factorial(__UpperCAmelCase ) print(F'the value at {value} is {summ}' ) if __name__ == "__main__": main()
356
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ : Union[str, Any] = None try: import msvcrt except ImportError: lowerCAmelCase_ : Tuple = None try: import fcntl except ImportError: lowerCAmelCase_ : Optional[int] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ : Any = OSError # Data # ------------------------------------------------ lowerCAmelCase_ : Tuple = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] lowerCAmelCase_ : Optional[int] = '3.0.12' lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( ) -> Optional[int]: global _logger _a = _logger or logging.getLogger(__name__ ) return _logger class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict , __a : Optional[Any] ): _a = lock_file return None def __str__( self : Any ): _a = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , __a : Optional[int] ): _a = lock return None def __enter__( self : str ): return self.lock def __exit__( self : List[Any] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): self.lock.release() return None class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] , __a : Optional[int]=-1 , __a : Tuple=None ): _a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long _a = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. _a = 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. _a = None # The default timeout value. _a = timeout # We use this lock primarily for the lock counter. _a = 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. _a = 0 return None @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file @property def UpperCamelCase__ ( self : List[Any] ): return self._timeout @timeout.setter def UpperCamelCase__ ( self : int , __a : List[Any] ): _a = float(__a ) return None def UpperCamelCase__ ( self : Dict ): raise NotImplementedError() def UpperCamelCase__ ( self : str ): raise NotImplementedError() @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file_fd is not None def UpperCamelCase__ ( self : int , __a : int=None , __a : Tuple=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: _a = 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 _a = id(self ) _a = self._lock_file _a = 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(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: _a = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: _a = id(self ) _a = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() _a = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : List[Any] ): self.acquire() return self def __exit__( self : str , __a : str , __a : Dict , __a : Dict ): self.release() return None def __del__( self : int ): self.release(force=__a ) return None def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): _a = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: _a = os.path.dirname(__a ) _a = str(hash(__a ) ) _a = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , __a : str , __a : List[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) _a = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def UpperCamelCase__ ( self : int ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Optional[Any] ): _a = self._lock_file_fd _a = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=-1 , __a : int=None ): _a = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def UpperCamelCase__ ( self : Any ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC _a = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Tuple ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition _a = self._lock_file_fd _a = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): _a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: _a = fd return None def UpperCamelCase__ ( self : Union[str, Any] ): os.close(self._lock_file_fd ) _a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ : str = None if msvcrt: lowerCAmelCase_ : List[str] = WindowsFileLock elif fcntl: lowerCAmelCase_ : List[str] = UnixFileLock else: lowerCAmelCase_ : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
346
0
'''simple docstring''' import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __SCREAMING_SNAKE_CASE (A__ , unittest.TestCase ): """simple docstring""" __a ='hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def UpperCamelCase__ ( self : Dict , __a : Union[str, Any]=0 ): _a = np.random.RandomState(lowerCamelCase__ ) _a = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def UpperCamelCase__ ( self : Any ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.65072, 0.58492, 0.48219, 0.55521, 0.53180, 0.55939, 0.50697, 0.39800, 0.46455] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : List[str] ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) _a = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.65863, 0.59425, 0.49326, 0.56313, 0.53875, 0.56627, 0.51065, 0.39777, 0.46330] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : List[Any] ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) _a = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : str ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) _a = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : Optional[int] ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) _a = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.53817, 0.60812, 0.47384, 0.49530, 0.51894, 0.49814, 0.47984, 0.38958, 0.44271] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : Optional[Any] ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) _a = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = pipe(**lowerCamelCase__ ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) _a = np.array([0.53895, 0.60808, 0.47933, 0.49608, 0.51886, 0.49950, 0.48053, 0.38957, 0.44200] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : List[str] ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = 3 * [inputs["prompt"]] # forward _a = pipe(**lowerCamelCase__ ) _a = output.images[0, -3:, -3:, -1] _a = self.get_dummy_inputs() _a = 3 * [inputs.pop("prompt" )] _a = pipe.tokenizer( lowerCamelCase__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=lowerCamelCase__ , return_tensors="np" , ) _a = text_inputs["input_ids"] _a = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] _a = prompt_embeds # forward _a = pipe(**lowerCamelCase__ ) _a = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def UpperCamelCase__ ( self : int ): _a = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = self.get_dummy_inputs() _a = 3 * ["this is a negative prompt"] _a = negative_prompt _a = 3 * [inputs["prompt"]] # forward _a = pipe(**lowerCamelCase__ ) _a = output.images[0, -3:, -3:, -1] _a = self.get_dummy_inputs() _a = 3 * [inputs.pop("prompt" )] _a = [] for p in [prompt, negative_prompt]: _a = pipe.tokenizer( lowerCamelCase__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=lowerCamelCase__ , return_tensors="np" , ) _a = text_inputs["input_ids"] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) _a , _a = embeds # forward _a = pipe(**lowerCamelCase__ ) _a = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @property def UpperCamelCase__ ( self : Union[str, Any] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCamelCase__ ( self : Optional[Any] ): _a = ort.SessionOptions() _a = False return options def UpperCamelCase__ ( self : Union[str, Any] ): # using the PNDM scheduler by default _a = OnnxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = "A painting of a squirrel eating a burger" np.random.seed(0 ) _a = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" ) _a = output.images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _a = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self : Tuple ): _a = DDIMScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) _a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=lowerCamelCase__ , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = "open neural network exchange" _a = np.random.RandomState(0 ) _a = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=lowerCamelCase__ , output_type="np" ) _a = output.images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _a = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self : Optional[int] ): _a = LMSDiscreteScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) _a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=lowerCamelCase__ , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = "open neural network exchange" _a = np.random.RandomState(0 ) _a = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=lowerCamelCase__ , output_type="np" ) _a = output.images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _a = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self : Dict ): _a = 0 def test_callback_fn(__a : int , __a : Any , __a : Any ) -> None: _a = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) _a = latents[0, -3:, -3:, -1] _a = np.array( [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) _a = latents[0, -3:, -3:, -1] _a = np.array( [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 _a = False _a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _a = "Andromeda galaxy in a bottle" _a = np.random.RandomState(0 ) pipe( prompt=lowerCamelCase__ , num_inference_steps=5 , guidance_scale=7.5 , generator=lowerCamelCase__ , callback=lowerCamelCase__ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def UpperCamelCase__ ( self : Union[str, Any] ): _a = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) assert pipe.safety_checker is None _a = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCamelCase__ ) _a = OnnxStableDiffusionPipeline.from_pretrained(lowerCamelCase__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None _a = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None
357
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
0
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase_ : List[str] = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase_ : List[str] = direct_transformers_import(PATH_TO_TRANSFORMERS) lowerCAmelCase_ : Union[str, Any] = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase_ : Optional[int] = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)') lowerCAmelCase_ : List[Any] = { '''DecisionTransformerConfig''', '''EncoderDecoderConfig''', '''MusicgenConfig''', '''RagConfig''', '''SpeechEncoderDecoderConfig''', '''TimmBackboneConfig''', '''VisionEncoderDecoderConfig''', '''VisionTextDualEncoderConfig''', '''LlamaConfig''', } def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = None # source code of `config_class` _a = inspect.getsource(A_ ) _a = _re_checkpoint.findall(A_ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("/" ): _a = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link _a = F'https://huggingface.co/{ckpt_name}' if ckpt_link == ckpt_link_from_name: _a = ckpt_name break return checkpoint def _lowerCamelCase ( ) -> Optional[int]: _a = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue _a = get_checkpoint_from_config_class(A_ ) _a = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _a = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'The following configurations don\'t contain any valid checkpoint:\n{message}' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
358
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ : List[str] = TypeVar('T') lowerCAmelCase_ : Dict = TypeVar('U') class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Union[str, Any] , __a : T | None , __a : U | None ): _a = key _a = val _a = None _a = None def __repr__( self : Any ): return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Dict ): _a = DoubleLinkedListNode(__a , __a ) _a = DoubleLinkedListNode(__a , __a ) _a , _a = self.rear, self.head def __repr__( self : str ): _a = ["DoubleLinkedList"] _a = self.head while node.next is not None: rep.append(str(__a ) ) _a = node.next rep.append(str(self.rear ) ) return ",\n ".join(__a ) def UpperCamelCase__ ( self : int , __a : DoubleLinkedListNode[T, U] ): _a = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _a = node _a = previous _a = node _a = self.rear def UpperCamelCase__ ( self : Any , __a : DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None _a = node.next _a = node.prev _a = None _a = None return node class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" __a ={} def __init__( self : Union[str, Any] , __a : int ): _a = DoubleLinkedList() _a = capacity _a = 0 _a = 0 _a = 0 _a = {} def __repr__( self : Optional[int] ): return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self : str , __a : T ): return key in self.cache def UpperCamelCase__ ( self : str , __a : T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _a = self.cache[key] _a = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__a ) return node.val self.miss += 1 return None def UpperCamelCase__ ( self : Tuple , __a : T , __a : U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _a = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _a = DoubleLinkedListNode(__a , __a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _a = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _a = value self.list.add(__a ) @classmethod def UpperCamelCase__ ( cls : Tuple , __a : int = 1_28 ): def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _a = LRUCache(__a ) _a = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _a = func(*__a ) cls.decorator_function_to_instance_map[func].put(args[0] , __a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__a , "cache_info" , __a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available lowerCAmelCase_ : List[str] = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : int = ['HerbertTokenizerFast'] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys lowerCAmelCase_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
359
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowerCamelCase ( lowercase : str ) -> str: re.sub("<n>" , "" , lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowercase ) )
346
0
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowerCAmelCase_ : str = logging.get_logger(__name__) lowerCAmelCase_ : Optional[int] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) lowerCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) lowerCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) lowerCAmelCase_ : Optional[int] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) lowerCAmelCase_ : Tuple = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) lowerCAmelCase_ : str = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) lowerCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) lowerCAmelCase_ : Tuple = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) lowerCAmelCase_ : Tuple = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) lowerCAmelCase_ : Any = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) lowerCAmelCase_ : Any = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) lowerCAmelCase_ : Optional[Any] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) lowerCAmelCase_ : Tuple = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) lowerCAmelCase_ : Tuple = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) lowerCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) lowerCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) lowerCAmelCase_ : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) lowerCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) lowerCAmelCase_ : List[str] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) lowerCAmelCase_ : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) lowerCAmelCase_ : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) lowerCAmelCase_ : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase_ : List[str] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) lowerCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) lowerCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) lowerCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_MAPPING lowerCAmelCase_ : Optional[int] = auto_class_update(FlaxAutoModel) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_PRETRAINING_MAPPING lowerCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : str = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_MASKED_LM_MAPPING lowerCAmelCase_ : Optional[int] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCAmelCase_ : List[Any] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowerCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING lowerCAmelCase_ : List[Any] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING lowerCAmelCase_ : List[str] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING lowerCAmelCase_ : Any = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowerCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class __SCREAMING_SNAKE_CASE (_BaseAutoModelClass ): """simple docstring""" __a =FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING lowerCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
360
'''simple docstring''' import requests lowerCAmelCase_ : List[Any] = 'YOUR API KEY' def _lowerCamelCase ( lowercase : str , lowercase : str = giphy_api_key ) -> list: _a = "+".join(query.split() ) _a = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' _a = requests.get(lowercase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
346
0
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowerCAmelCase_ : List[Any] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowerCAmelCase_ : List[Any] = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowerCAmelCase_ : List[str] = parser.parse_args() if args.check_lib: lowerCAmelCase_ : int = importlib.import_module('transformers') lowerCAmelCase_ : Tuple = Path(transformers_module.__file__).parent else: lowerCAmelCase_ : str = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =BertGenerationTokenizer __a =False __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = BertGenerationTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ ( self : Tuple ): _a = "<s>" _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[str] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__a ) , 10_02 ) def UpperCamelCase__ ( self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def UpperCamelCase__ ( self : Tuple ): _a = BertGenerationTokenizer(__a , keep_accents=__a ) _a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [2_85, 46, 10, 1_70, 3_82] , ) _a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _a = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def UpperCamelCase__ ( self : Any ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def UpperCamelCase__ ( self : List[str] ): _a = "Hello World!" _a = [1_85_36, 22_60, 1_01] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def UpperCamelCase__ ( self : Optional[int] ): _a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def UpperCamelCase__ ( self : Tuple ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _a = list(self.big_tokenizer.get_vocab().keys() )[:10] _a = " ".join(__a ) _a = self.big_tokenizer.encode_plus(__a , return_tensors="pt" , return_token_type_ids=__a ) _a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__a ) _a = BertGenerationConfig() _a = BertGenerationEncoder(__a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def UpperCamelCase__ ( self : Optional[int] ): # fmt: off _a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
346
0
'''simple docstring''' from __future__ import annotations def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Optional[Any]: print(F'Vertex\tShortest Distance from vertex {src}' ) for i, d in enumerate(__lowerCAmelCase ): print(F'{i}\t\t{d}' ) def _lowerCamelCase ( lowercase : Any , lowercase : Any , lowercase : int ) -> Dict: for j in range(__lowerCAmelCase ): _a = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float("inf" ) and distance[u] + w < distance[v]: return True return False def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[int] , lowercase : Union[str, Any] , lowercase : Dict ) -> list[float]: _a = [float("inf" )] * vertex_count _a = 0.0 for _ in range(vertex_count - 1 ): for j in range(__lowerCAmelCase ): _a = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float("inf" ) and distance[u] + w < distance[v]: _a = distance[u] + w _a = check_negative_cycle(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if negative_cycle_exists: raise Exception("Negative cycle found" ) return distance if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase_ : Any = int(input('Enter number of vertices: ').strip()) lowerCAmelCase_ : List[Any] = int(input('Enter number of edges: ').strip()) lowerCAmelCase_ : Any = [{} for _ in range(E)] for i in range(E): print('Edge ', i + 1) lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[str] = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) lowerCAmelCase_ : Tuple = {'src': src, 'dst': dest, 'weight': weight} lowerCAmelCase_ : Tuple = int(input('\nEnter shortest path source:').strip()) lowerCAmelCase_ : Tuple = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
362
'''simple docstring''' def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Union[str, Any]: _enforce_args(lowercase , lowercase ) if n == 0: return 0 _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase ) ) return max_revue def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Tuple: _enforce_args(lowercase , lowercase ) _a = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase , lowercase , lowercase ) def _lowerCamelCase ( lowercase : int , lowercase : list , lowercase : list ) -> List[str]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase , lowercase ) , ) _a = max_revenue return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Any: _enforce_args(lowercase , lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _a = [float("-inf" ) for _ in range(n + 1 )] _a = 0 for i in range(1 , n + 1 ): _a = max_rev[i] for j in range(1 , i + 1 ): _a = max(lowercase , prices[j - 1] + max_rev[i - j] ) _a = max_revenue_i return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Dict: if n < 0: _a = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): _a = ( "Each integral piece of rod must have a corresponding price. " F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def _lowerCamelCase ( ) -> Any: _a = [6, 10, 12, 15, 20, 23] _a = len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _a = 36 _a = top_down_cut_rod(lowercase , lowercase ) _a = bottom_up_cut_rod(lowercase , lowercase ) _a = naive_cut_rod_recursive(lowercase , lowercase ) 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()
346
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) def _lowerCamelCase ( lowercase : Union[tf.Tensor, np.ndarray] ) -> List[int]: if isinstance(_lowercase , np.ndarray ): return list(tensor.shape ) _a = tf.shape(_lowercase ) if tensor.shape == tf.TensorShape(_lowercase ): return dynamic _a = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(_lowercase )] def _lowerCamelCase ( lowercase : tf.Tensor , lowercase : Optional[int] = None , lowercase : Optional[str] = None ) -> tf.Tensor: return tf.nn.softmax(logits=logits + 1E-9 , axis=_lowercase , name=_lowercase ) def _lowerCamelCase ( lowercase : List[Any] , lowercase : Optional[int] , lowercase : Tuple , lowercase : Any=1E-5 , lowercase : Union[str, Any]=-1 ) -> List[str]: if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_lowercase , _lowercase ): raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis." ) # Get mean and variance on the axis to be normalized _a = tf.nn.moments(_lowercase , axes=[axis] , keepdims=_lowercase ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis _a = [1] * inputs.shape.rank _a = shape_list(_lowercase )[axis] _a = tf.reshape(_lowercase , _lowercase ) _a = tf.reshape(_lowercase , _lowercase ) # Compute layer normalization using the batch_normalization # function. _a = tf.nn.batch_normalization( _lowercase , _lowercase , _lowercase , offset=_lowercase , scale=_lowercase , variance_epsilon=_lowercase , ) return outputs def _lowerCamelCase ( lowercase : Any , lowercase : int=0 , lowercase : Optional[Any]=-1 ) -> Optional[Any]: if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input _a = tf.shape(_lowercase ) _a = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) _a = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(_lowercase , _lowercase ) def _lowerCamelCase ( lowercase : tf.Tensor ) -> tf.Tensor: if not isinstance(_lowercase , tf.Tensor ): _a = tf.convert_to_tensor(_lowercase ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: _a = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: _a = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) _a = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _lowerCamelCase ( lowercase : tf.Tensor , lowercase : int , lowercase : str = "input_ids" ) -> None: tf.debugging.assert_less( _lowercase , tf.cast(_lowercase , dtype=tensor.dtype ) , message=( F'The maximum value of {tensor_name} ({tf.math.reduce_max(_lowercase )}) must be smaller than the embedding ' F'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.' ) , ) def _lowerCamelCase ( lowercase : int , lowercase : Dict , lowercase : str ) -> str: _a = 6_4512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. _a = [x for x in data if len(_lowercase ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( "The following attributes cannot be saved to HDF5 file because " F'they are larger than {HDF5_OBJECT_HEADER_LIMIT} ' F'bytes: {bad_attributes}' ) _a = np.asarray(_lowercase ) _a = 1 _a = np.array_split(_lowercase , _lowercase ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 _a = np.array_split(_lowercase , _lowercase ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(_lowercase ): _a = chunk_data else: _a = data def _lowerCamelCase ( lowercase : List[Any] , lowercase : Optional[int] ) -> int: if name in group.attrs: _a = [n.decode("utf8" ) if hasattr(_lowercase , "decode" ) else n for n in group.attrs[name]] else: _a = [] _a = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("utf8" ) if hasattr(_lowercase , "decode" ) else n for n in group.attrs["%s%d" % (name, chunk_id)]] ) chunk_id += 1 return data def _lowerCamelCase ( lowercase : List[Any] ) -> str: def _expand_single_ad_tensor(lowercase : Optional[Any] ): if isinstance(_lowercase , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(_lowercase , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , _lowercase )
363
'''simple docstring''' 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_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , *__a : Optional[int] , **__a : List[str] ): super().__init__(*__a , **__a ) self.check_model_type(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : int=None , __a : Optional[Any]=None , **__a : List[Any] ): _a , _a = {}, {} if padding is not None: _a = padding if truncation is not None: _a = truncation if top_k is not None: _a = top_k return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __a : Union["Image.Image", str] , __a : str = None , **__a : Any ): if isinstance(__a , (Image.Image, str) ) and isinstance(__a , __a ): _a = {"image": image, "question": question} else: _a = image _a = super().__call__(__a , **__a ) return results def UpperCamelCase__ ( self : Tuple , __a : Tuple , __a : Optional[Any]=False , __a : List[Any]=False ): _a = load_image(inputs["image"] ) _a = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=__a , truncation=__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) model_inputs.update(__a ) return model_inputs def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.sigmoid()[0] _a , _a = probs.topk(__a ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
346
0
'''simple docstring''' import os import sys lowerCAmelCase_ : int = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) lowerCAmelCase_ : List[Any] = [ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def _lowerCamelCase ( *lowercase : Union[str, Any] , **lowercase : int ) -> List[Any]: return AutoConfig.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoTokenizer.__doc__ ) def _lowerCamelCase ( *lowercase : List[Any] , **lowercase : Optional[int] ) -> Tuple: return AutoTokenizer.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoModel.__doc__ ) def _lowerCamelCase ( *lowercase : List[str] , **lowercase : List[str] ) -> Union[str, Any]: return AutoModel.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def _lowerCamelCase ( *lowercase : int , **lowercase : str ) -> int: return AutoModelForCausalLM.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def _lowerCamelCase ( *lowercase : List[str] , **lowercase : Tuple ) -> Dict: return AutoModelForMaskedLM.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def _lowerCamelCase ( *lowercase : Optional[int] , **lowercase : Dict ) -> str: return AutoModelForSequenceClassification.from_pretrained(*lowercase , **lowercase ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def _lowerCamelCase ( *lowercase : Dict , **lowercase : str ) -> int: return AutoModelForQuestionAnswering.from_pretrained(*lowercase , **lowercase )
364
'''simple docstring''' from random import randint, random def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : bool = False , lowercase : int = 5 , ) -> list: _a = [[-1] * number_of_cells] # Create a highway without any car _a = 0 _a = max(lowercase , 0 ) while i < number_of_cells: _a = ( randint(0 , lowercase ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( lowercase : list , lowercase : int ) -> int: _a = 0 _a = highway_now[car_index + 1 :] for cell in range(len(lowercase ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(lowercase , -1 ) def _lowerCamelCase ( lowercase : list , lowercase : float , lowercase : int ) -> list: _a = len(lowercase ) # Beforce calculations, the highway is empty _a = [-1] * number_of_cells for car_index in range(lowercase ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _a = min(highway_now[car_index] + 1 , lowercase ) # Number of empty cell before the next car _a = get_distance(lowercase , lowercase ) - 1 # We can't have the car causing an accident _a = min(next_highway[car_index] , lowercase ) if random() < probability: # Randomly, a driver will slow down _a = max(next_highway[car_index] - 1 , 0 ) return next_highway def _lowerCamelCase ( lowercase : list , lowercase : int , lowercase : float , lowercase : int ) -> list: _a = len(highway[0] ) for i in range(lowercase ): _a = update(highway[i] , lowercase , lowercase ) _a = [-1] * number_of_cells for car_index in range(lowercase ): _a = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _a = (car_index + speed) % number_of_cells # Commit the change of position _a = speed highway.append(lowercase ) return highway if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' from __future__ import annotations class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] ): _a = data _a = None _a = None def _lowerCamelCase ( lowercase : Node | None ) -> None: # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _lowerCamelCase ( lowercase : Node | None ) -> int: return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def _lowerCamelCase ( lowercase : Node ) -> bool: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _lowerCamelCase ( ) -> None: # Main function for testing. _a = Node(1 ) _a = Node(2 ) _a = Node(3 ) _a = Node(4 ) _a = Node(5 ) _a = Node(6 ) _a = Node(7 ) _a = Node(8 ) _a = Node(9 ) print(is_full_binary_tree(snake_case__ ) ) print(depth_of_tree(snake_case__ ) ) print("Tree is: " ) display(snake_case__ ) if __name__ == "__main__": main()
365
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
346
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCAmelCase_ : List[Any] = logging.get_logger(__name__) lowerCAmelCase_ : Dict = { 'post_extract_proj': 'feature_projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.upsample.0': 'encoder.upsample.projection', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'layer_norm', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def _lowerCamelCase ( lowercase : List[str] , lowercase : str , lowercase : Optional[int] , lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Dict: for attribute in key.split("." ): _a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) if weight_type is not None: _a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ).shape else: _a = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": _a = value elif weight_type == "weight_g": _a = value elif weight_type == "weight_v": _a = value elif weight_type == "bias": _a = value else: _a = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def _lowerCamelCase ( lowercase : str , lowercase : Any , lowercase : Optional[Any] ) -> Optional[int]: _a = [] _a = fairseq_model.state_dict() _a = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _a = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , hf_model.config.feat_extract_norm == "group" , ) _a = True else: for key, mapped_key in MAPPING.items(): _a = """sew.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: _a = True if "*" in mapped_key: _a = name.split(lowerCAmelCase__ )[0].split("." )[-2] _a = mapped_key.replace("*" , lowerCAmelCase__ ) if "weight_g" in name: _a = """weight_g""" elif "weight_v" in name: _a = """weight_v""" elif "weight" in name: _a = """weight""" elif "bias" in name: _a = """bias""" else: _a = None set_recursively(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(F'Unused weights: {unused_weights}' ) def _lowerCamelCase ( lowercase : int , lowercase : Tuple , lowercase : str , lowercase : Tuple , lowercase : Any ) -> Optional[Any]: _a = full_name.split("conv_layers." )[-1] _a = name.split("." ) _a = int(items[0] ) _a = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) _a = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) _a = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) _a = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) _a = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowerCAmelCase__ ) def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict ) -> int: _a = SEWConfig() if is_finetuned: _a = model.wav_encoder.wav_model.cfg else: _a = model.cfg _a = fs_config.conv_bias _a = eval(fs_config.conv_feature_layers ) _a = [x[0] for x in conv_layers] _a = [x[1] for x in conv_layers] _a = [x[2] for x in conv_layers] _a = """gelu""" _a = """layer""" if fs_config.extractor_mode == """layer_norm""" else """group""" _a = 0.0 _a = fs_config.activation_fn.name _a = fs_config.encoder_embed_dim _a = 0.02 _a = fs_config.encoder_ffn_embed_dim _a = 1E-5 _a = fs_config.encoder_layerdrop _a = fs_config.encoder_attention_heads _a = fs_config.conv_pos_groups _a = fs_config.conv_pos _a = len(lowerCAmelCase__ ) _a = fs_config.encoder_layers _a = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: _a = model.cfg _a = fs_config.final_dropout _a = fs_config.layerdrop _a = fs_config.activation_dropout _a = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 _a = fs_config.attention_dropout _a = fs_config.dropout_input _a = fs_config.dropout _a = fs_config.mask_channel_length _a = fs_config.mask_channel_prob _a = fs_config.mask_length _a = fs_config.mask_prob _a = """Wav2Vec2FeatureExtractor""" _a = """Wav2Vec2CTCTokenizer""" return config @torch.no_grad() def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict , lowercase : Optional[int]=None , lowercase : List[str]=None , lowercase : List[Any]=True ) -> Optional[int]: if is_finetuned: _a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: _a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: _a = SEWConfig.from_pretrained(lowerCAmelCase__ ) else: _a = convert_config(model[0] , lowerCAmelCase__ ) _a = model[0].eval() _a = True if config.feat_extract_norm == """layer""" else False _a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) if is_finetuned: if dict_path: _a = Dictionary.load(lowerCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a = target_dict.pad_index _a = target_dict.bos_index _a = target_dict.pad_index _a = target_dict.bos_index _a = target_dict.eos_index _a = len(target_dict.symbols ) _a = os.path.join(lowerCAmelCase__ , "vocab.json" ) if not os.path.isdir(lowerCAmelCase__ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(lowerCAmelCase__ ) ) return os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , lowerCAmelCase__ ) _a = WavaVecaCTCTokenizer( lowerCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=lowerCAmelCase__ , ) _a = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) _a = SEWForCTC(lowerCAmelCase__ ) else: _a = SEWModel(lowerCAmelCase__ ) feature_extractor.save_pretrained(lowerCAmelCase__ ) recursively_load_weights(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowerCAmelCase_ : Tuple = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--is_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) lowerCAmelCase_ : str = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0
'''simple docstring''' import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ : int = logging.get_logger(__name__) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : str ) -> List[Any]: _a = RobertaPreLayerNormConfig.from_pretrained( SCREAMING_SNAKE_CASE__ , architectures=["RobertaPreLayerNormForMaskedLM"] ) # convert state_dict _a = torch.load(hf_hub_download(repo_id=SCREAMING_SNAKE_CASE__ , filename="pytorch_model.bin" ) ) _a = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith("roberta." ): _a = '''roberta_prelayernorm.''' + tensor_key[len("roberta." ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith(".self.LayerNorm.weight" ) or tensor_key.endswith(".self.LayerNorm.bias" ): continue _a = tensor_value _a = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ , state_dict=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) # convert tokenizer _a = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowerCAmelCase_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint-repo', default=None, type=str, required=True, help='Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowerCAmelCase_ : Union[str, Any] = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
367
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ : List[Any] = logging.getLogger(__name__) lowerCAmelCase_ : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowerCAmelCase_ : int = {'facebook/bart-base': BartTokenizer} def _lowerCamelCase ( ) -> Union[str, Any]: _a = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=lowercase , default=lowercase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=lowercase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowercase , default=lowercase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowercase , ) parser.add_argument( "--config_name" , type=lowercase , default=lowercase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowercase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowercase , default=lowercase , help="Where to store the final ONNX file." ) _a = parser.parse_args() return args def _lowerCamelCase ( lowercase : Any , lowercase : Tuple="cpu" ) -> Optional[Any]: _a = model_dict[model_name].from_pretrained(lowercase ).to(lowercase ) _a = tokenizer_dict[model_name].from_pretrained(lowercase ) if model_name in ["facebook/bart-base"]: _a = 0 _a = None _a = 0 return huggingface_model, tokenizer def _lowerCamelCase ( lowercase : List[str] , lowercase : Tuple , lowercase : int , lowercase : Any , lowercase : Dict ) -> Any: model.eval() _a = None _a = torch.jit.script(BARTBeamSearchGenerator(lowercase ) ) with torch.no_grad(): _a = "My friends are cool but they eat too many carbs." _a = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) _a = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowercase , max_length=lowercase , early_stopping=lowercase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowercase , ) logger.info("Model exported to {}".format(lowercase ) ) _a = remove_dup_initializers(os.path.abspath(lowercase ) ) logger.info("Deduplicated and optimized model written to {}".format(lowercase ) ) _a = onnxruntime.InferenceSession(lowercase ) _a = ort_sess.run( lowercase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowercase ), "max_length": np.array(lowercase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def _lowerCamelCase ( ) -> Any: _a = parse_args() _a = 5 _a = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _a = torch.device(args.device ) _a , _a = load_model_tokenizer(args.model_name_or_path , lowercase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(lowercase ) if args.max_length: _a = args.max_length if args.num_beams: _a = args.num_beams if args.output_file_path: _a = args.output_file_path else: _a = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(lowercase , lowercase , lowercase , lowercase , lowercase ) if __name__ == "__main__": main()
346
0
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : int = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE (_a , unittest.TestCase ): """simple docstring""" __a =PegasusTokenizer __a =PegasusTokenizerFast __a =True __a =True def UpperCamelCase__ ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing _a = PegasusTokenizer(__a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase__ ( self : str ): return PegasusTokenizer.from_pretrained("google/pegasus-large" ) def UpperCamelCase__ ( self : Optional[Any] , **__a : Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : List[Any] , __a : int ): return ("This is a test", "This is a test") def UpperCamelCase__ ( self : Any ): _a = '</s>' _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[Any] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "</s>" ) self.assertEqual(vocab_keys[-1] , "v" ) self.assertEqual(len(__a ) , 11_03 ) def UpperCamelCase__ ( self : Optional[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 11_03 ) def UpperCamelCase__ ( self : str ): _a = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _a = self.tokenizer_class.from_pretrained(self.tmpdirname ) _a = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) _a = rust_tokenizer([raw_input_str] , return_tensors=__a , add_special_tokens=__a ).input_ids[0] _a = py_tokenizer([raw_input_str] , return_tensors=__a , add_special_tokens=__a ).input_ids[0] self.assertListEqual(__a , __a ) def UpperCamelCase__ ( self : List[Any] ): _a = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word _a = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' _a = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] _a = tokenizer([raw_input_str] , return_tensors=__a ).input_ids[0] self.assertListEqual(__a , __a ) def UpperCamelCase__ ( self : Any ): _a = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 _a = 'To ensure a smooth flow of bank resolutions.' _a = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] _a = tokenizer([raw_input_str] , return_tensors=__a ).input_ids[0] self.assertListEqual(__a , __a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def UpperCamelCase__ ( self : Dict ): _a = ['This is going to be way too long.' * 1_50, 'short example'] _a = ['not super long but more than 5 tokens', 'tiny'] _a = self._large_tokenizer(__a , padding=__a , truncation=__a , return_tensors="pt" ) _a = self._large_tokenizer( text_target=__a , max_length=5 , padding=__a , truncation=__a , return_tensors="pt" ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(__a ) == 2 # input_ids, attention_mask. @slow def UpperCamelCase__ ( self : List[Any] ): _a = {'input_ids': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bigbird-pegasus-large-arxiv" , revision="ba85d0851d708441f91440d509690f1ab6353415" , ) @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE (_a , unittest.TestCase ): """simple docstring""" __a =PegasusTokenizer __a =PegasusTokenizerFast __a =True __a =True def UpperCamelCase__ ( self : Union[str, Any] ): super().setUp() # We have a SentencePiece fixture for testing _a = PegasusTokenizer(__a , offset=0 , mask_token_sent=__a , mask_token="[MASK]" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase__ ( self : Tuple ): return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv" ) def UpperCamelCase__ ( self : Dict , **__a : List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : List[str] , __a : Tuple ): return ("This is a test", "This is a test") def UpperCamelCase__ ( self : List[Any] ): _a = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _a = self.tokenizer_class.from_pretrained(self.tmpdirname ) _a = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) _a = rust_tokenizer([raw_input_str] , return_tensors=__a , add_special_tokens=__a ).input_ids[0] _a = py_tokenizer([raw_input_str] , return_tensors=__a , add_special_tokens=__a ).input_ids[0] self.assertListEqual(__a , __a ) @require_torch def UpperCamelCase__ ( self : Tuple ): _a = ['This is going to be way too long.' * 10_00, 'short example'] _a = ['not super long but more than 5 tokens', 'tiny'] _a = self._large_tokenizer(__a , padding=__a , truncation=__a , return_tensors="pt" ) _a = self._large_tokenizer( text_target=__a , max_length=5 , padding=__a , truncation=__a , return_tensors="pt" ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(__a ) == 2 # input_ids, attention_mask. def UpperCamelCase__ ( self : Tuple ): _a = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) _a = self._large_tokenizer(__a ).input_ids self.assertListEqual( __a , [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1] , )
368
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCAmelCase_ : Dict = abspath(join(dirname(dirname(dirname(__file__))), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _lowerCamelCase ( lowercase : str ) -> Optional[int]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase ) def _lowerCamelCase ( lowercase : Dict ) -> str: from transformers.testing_utils import pytest_terminal_summary_main _a = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(lowercase , id=lowercase )
346
0
'''simple docstring''' import os lowerCAmelCase_ : Any = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 1_00, 'D': 5_00, 'M': 10_00} def _lowerCamelCase ( lowercase : str ) -> int: _a = 0 _a = 0 while index < len(__UpperCamelCase ) - 1: _a = SYMBOLS[numerals[index]] _a = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def _lowerCamelCase ( lowercase : int ) -> Tuple: _a = "" _a = num // 1000 numerals += m_count * "M" num %= 1000 _a = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 _a = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def _lowerCamelCase ( lowercase : str = "/p089_roman.txt" ) -> Tuple: _a = 0 with open(os.path.dirname(__UpperCamelCase ) + roman_numerals_filename ) as filea: _a = filea.readlines() for line in lines: _a = line.strip() _a = parse_roman_numerals(__UpperCamelCase ) _a = generate_roman_numerals(__UpperCamelCase ) savings += len(__UpperCamelCase ) - len(__UpperCamelCase ) return savings if __name__ == "__main__": print(f"""{solution() = }""")
369
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @register_to_config def __init__( self : List[Any] , __a : int , __a : int , __a : int , __a : float , __a : int , __a : int , __a : int , __a : int , __a : str , __a : bool = False , ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.Embedding(__a , __a ) _a = False _a = nn.Dropout(p=__a ) _a = TaConfig( vocab_size=__a , d_model=__a , num_heads=__a , d_kv=__a , d_ff=__a , dropout_rate=__a , feed_forward_proj=__a , is_decoder=__a , is_encoder_decoder=__a , ) _a = nn.ModuleList() for lyr_num in range(__a ): _a = TaBlock(__a ) self.encoders.append(__a ) _a = TaLayerNorm(__a ) _a = nn.Dropout(p=__a ) def UpperCamelCase__ ( self : str , __a : Union[str, Any] , __a : Dict ): _a = self.token_embedder(__a ) _a = encoder_input_tokens.shape[1] _a = torch.arange(__a , device=encoder_input_tokens.device ) x += self.position_encoding(__a ) _a = self.dropout_pre(__a ) # inverted the attention mask _a = encoder_input_tokens.size() _a = self.get_extended_attention_mask(__a , __a ) for lyr in self.encoders: _a = lyr(__a , __a )[0] _a = self.layer_norm(__a ) return self.dropout_post(__a ), encoder_inputs_mask
346
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowerCAmelCase_ : str = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE (_lowerCAmelCase ): """simple docstring""" __a =["pixel_values"] def __init__( self : Tuple , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : bool = True , __a : Dict[str, int] = None , __a : bool = True , __a : Union[int, float] = 1 / 2_55 , __a : bool = True , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = True , **__a : int , ): super().__init__(**_lowercase ) _a = size if size is not None else {"shortest_edge": 2_24} _a = get_size_dict(_lowercase , default_to_square=_lowercase ) _a = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} _a = get_size_dict(_lowercase , default_to_square=_lowercase , param_name="crop_size" ) _a = do_resize _a = size _a = resample _a = do_center_crop _a = crop_size _a = do_rescale _a = rescale_factor _a = do_normalize _a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _a = image_std if image_std is not None else OPENAI_CLIP_STD _a = do_convert_rgb def UpperCamelCase__ ( self : Union[str, Any] , __a : np.ndarray , __a : Dict[str, int] , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Union[str, Any] , ): _a = get_size_dict(_lowercase , default_to_square=_lowercase ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) _a = get_resize_output_image_size(_lowercase , size=size["shortest_edge"] , default_to_square=_lowercase ) return resize(_lowercase , size=_lowercase , resample=_lowercase , data_format=_lowercase , **_lowercase ) def UpperCamelCase__ ( self : Any , __a : np.ndarray , __a : Dict[str, int] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : str , ): _a = get_size_dict(_lowercase ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(_lowercase , size=(size["height"], size["width"]) , data_format=_lowercase , **_lowercase ) def UpperCamelCase__ ( self : Optional[Any] , __a : np.ndarray , __a : Union[int, float] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Dict , ): return rescale(_lowercase , scale=_lowercase , data_format=_lowercase , **_lowercase ) def UpperCamelCase__ ( self : Any , __a : np.ndarray , __a : Union[float, List[float]] , __a : Union[float, List[float]] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Union[str, Any] , ): return normalize(_lowercase , mean=_lowercase , std=_lowercase , data_format=_lowercase , **_lowercase ) def UpperCamelCase__ ( self : Dict , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : int = None , __a : bool = None , __a : float = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = None , __a : Optional[Union[str, TensorType]] = None , __a : Optional[ChannelDimension] = ChannelDimension.FIRST , **__a : Any , ): _a = do_resize if do_resize is not None else self.do_resize _a = size if size is not None else self.size _a = get_size_dict(_lowercase , param_name="size" , default_to_square=_lowercase ) _a = resample if resample is not None else self.resample _a = do_center_crop if do_center_crop is not None else self.do_center_crop _a = crop_size if crop_size is not None else self.crop_size _a = get_size_dict(_lowercase , param_name="crop_size" , default_to_square=_lowercase ) _a = do_rescale if do_rescale is not None else self.do_rescale _a = rescale_factor if rescale_factor is not None else self.rescale_factor _a = do_normalize if do_normalize is not None else self.do_normalize _a = image_mean if image_mean is not None else self.image_mean _a = image_std if image_std is not None else self.image_std _a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _a = make_list_of_images(_lowercase ) if not valid_images(_lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: _a = [convert_to_rgb(_lowercase ) for image in images] # All transformations expect numpy arrays. _a = [to_numpy_array(_lowercase ) for image in images] if do_resize: _a = [self.resize(image=_lowercase , size=_lowercase , resample=_lowercase ) for image in images] if do_center_crop: _a = [self.center_crop(image=_lowercase , size=_lowercase ) for image in images] if do_rescale: _a = [self.rescale(image=_lowercase , scale=_lowercase ) for image in images] if do_normalize: _a = [self.normalize(image=_lowercase , mean=_lowercase , std=_lowercase ) for image in images] _a = [to_channel_dimension_format(_lowercase , _lowercase ) for image in images] _a = {"pixel_values": images} return BatchFeature(data=_lowercase , tensor_type=_lowercase )
370
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Any: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : List[str] = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Union[str, Any]: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": _a = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Dict , lowercase : Dict ) -> str: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Tuple , __a : Optional[int] , __a : Any ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Tuple , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Dict=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : List[Any] , __a : Dict ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Union[str, Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Optional[int] , __a : pl.Trainer , __a : str ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
346
0
'''simple docstring''' import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : List[Any] ): _a = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) _a = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) model.to(__lowerCAmelCase ) from datasets import load_dataset _a = load_dataset("nielsr/rvlcdip-demo" ) _a = dataset["train"][0]["image"].convert("RGB" ) _a = image_processor(__lowerCAmelCase , return_tensors="pt" ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _a = model(**__lowerCAmelCase ) _a = outputs.logits _a = torch.Size((1, 16) ) self.assertEqual(logits.shape , __lowerCAmelCase ) _a = torch.tensor( [-0.4158, -0.4092, -0.4347] , device=__lowerCAmelCase , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , __lowerCAmelCase , atol=1e-4 ) )
371
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): lowerCAmelCase_ : str = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ : Union[str, Any] = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = (images / 2 + 0.5).clamp(0 , 1 ) _a = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _a = numpy_to_pil(lowercase ) return images def _lowerCamelCase ( lowercase : int ) -> List[Any]: if images.ndim == 3: _a = images[None, ...] _a = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _a = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: _a = [Image.fromarray(lowercase ) for image in images] return pil_images
346
0
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __SCREAMING_SNAKE_CASE (snake_case_ ): """simple docstring""" __a ="" __a ="hf-legacy" # "hf://"" is reserved for hffs def __init__( self : str , __a : Optional[DatasetInfo] = None , __a : Optional[str] = None , **__a : Optional[Any] , ): super().__init__(self , **_A ) _a = repo_info _a = token _a = None def UpperCamelCase__ ( self : List[str] ): if self.dir_cache is None: _a = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _a = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_A ): {"name": str(_A ), "size": None, "type": "directory"} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def UpperCamelCase__ ( self : Union[str, Any] , __a : str , __a : str = "rb" , **__a : Tuple , ): if not isinstance(self.repo_info , _A ): raise NotImplementedError(f'Open is only implemented for dataset repositories, but got {self.repo_info}' ) _a = hf_hub_url(self.repo_info.id , _A , revision=self.repo_info.sha ) return fsspec.open( _A , mode=_A , headers=get_authentication_headers_for_url(_A , use_auth_token=self.token ) , client_kwargs={"trust_env": True} , ).open() def UpperCamelCase__ ( self : int , __a : Tuple , **__a : str ): self._get_dirs() _a = self._strip_protocol(_A ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_A ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : Union[str, Any]=False , **__a : Any ): self._get_dirs() _a = PurePosixPath(path.strip("/" ) ) _a = {} for p, f in self.dir_cache.items(): _a = PurePosixPath(p.strip("/" ) ) _a = p.parent if root == path: _a = f _a = list(paths.values() ) if detail: return out else: return sorted(f["name"] for f in out )
350
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: _a = 10 _a = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) _a = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(lowercase ) ), } , features=lowercase , ) return dataset @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=lowercase ) return filename # FILE_CONTENT + files lowerCAmelCase_ : Union[str, Any] = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = tmp_path_factory.mktemp("data" ) / "file.txt" _a = FILE_CONTENT with open(lowercase , "w" ) as f: f.write(lowercase ) return filename @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: import bza _a = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" _a = bytes(lowercase , "utf-8" ) with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Optional[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) _a = bytes(lowercase , "utf-8" ) with gzip.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Union[str, Any]: if datasets.config.LZ4_AVAILABLE: import lza.frame _a = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" _a = bytes(lowercase , "utf-8" ) with lza.frame.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Tuple ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _a = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(lowercase , "w" ) as archive: archive.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[Any] ) -> Dict: import tarfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any ) -> Union[str, Any]: import lzma _a = tmp_path_factory.mktemp("data" ) / "file.txt.xz" _a = bytes(lowercase , "utf-8" ) with lzma.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int , lowercase : Any ) -> Union[str, Any]: import zipfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> List[str]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _a = tmp_path_factory.mktemp("data" ) / "file.txt.zst" _a = bytes(lowercase , "utf-8" ) with zstd.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "file.xml" _a = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(lowercase , "w" ) as f: f.write(lowercase ) return filename lowerCAmelCase_ : Optional[int] = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] lowerCAmelCase_ : Dict = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } lowerCAmelCase_ : Dict = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> str: _a = datasets.Dataset.from_dict(lowercase ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> Dict: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(lowercase ) ) as con: _a = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> int: import bza _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(lowercase , "rb" ) as f: _a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Any , lowercase : Any ) -> List[str]: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Any , lowercase : List[Any] ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(lowercase , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Optional[Any] , lowercase : int ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) _a = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(lowercase , "wb" ) as f: _a = pq.ParquetWriter(lowercase , schema=lowercase ) _a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase ) )] for k in DATA[0]} , schema=lowercase ) writer.write_table(lowercase ) writer.close() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA_DICT_OF_LISTS} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> List[str]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_312: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> int: _a = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_STR: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Tuple: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : List[Any] ) -> List[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[Any] , lowercase : int ) -> str: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : int , lowercase : List[Any] ) -> Optional[int]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] , lowercase : str ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : Any , lowercase : Optional[int] ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str , lowercase : List[str] , lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> str: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Dict: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Dict: _a = ["0", "1", "2", "3"] _a = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Union[str, Any] , lowercase : Any ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : List[str] , lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int , lowercase : str ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename("unsupported.ext" ) ) f.write(lowercase , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Any: _a = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(lowercase , "w" , encoding="utf-8" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[Any]: return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: _a = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
346
0
'''simple docstring''' import string def _lowerCamelCase ( lowercase : str ) -> Union[str, Any]: for key in range(len(string.ascii_uppercase ) ): _a = """""" for symbol in message: if symbol in string.ascii_uppercase: _a = string.ascii_uppercase.find(A__ ) _a = num - key if num < 0: _a = num + len(string.ascii_uppercase ) _a = translated + string.ascii_uppercase[num] else: _a = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def _lowerCamelCase ( ) -> str: _a = input("Encrypted message: " ) _a = message.upper() decrypt(A__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
351
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='LayoutLMv2ImageProcessor' __a =('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Dict , __a : int=None , __a : List[Any]=None , **__a : str ): if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self : Optional[int] , __a : Optional[Any] , __a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __a : Union[List[List[int]], List[List[List[int]]]] = None , __a : Optional[Union[List[int], List[List[int]]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = None , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Optional[Any] , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor _a = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): _a = [text] # add batch dimension (as the image processor always adds a batch dimension) _a = features["words"] _a = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values _a = features.pop("pixel_values" ) if return_overflowing_tokens is True: _a = self.get_overflowing_images(__a , encoded_inputs["overflow_to_sample_mapping"] ) _a = images return encoded_inputs def UpperCamelCase__ ( self : int , __a : List[Any] , __a : int ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(__a )} and {len(__a )}' ) return images_with_overflow def UpperCamelCase__ ( self : Optional[Any] , *__a : Dict , **__a : Union[str, Any] ): return self.tokenizer.batch_decode(*__a , **__a ) def UpperCamelCase__ ( self : Union[str, Any] , *__a : Optional[int] , **__a : Optional[Any] ): return self.tokenizer.decode(*__a , **__a ) @property def UpperCamelCase__ ( self : int ): return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase__ ( self : List[Any] ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , ) return self.image_processor_class @property def UpperCamelCase__ ( self : int ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , ) return self.image_processor
346
0
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : Optional[Any] ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[Any] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : List[Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Any ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(snake_case_ , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[str] ): _a = self.shape _a = int(np.prod(snake_case_ ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(snake_case_ ) _a = rays.view(snake_case_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Union[str, Any] , __a : torch.Tensor ): _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(snake_case_ , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(snake_case_ , -1 , 2 ) _a = ( self.z.view(snake_case_ , 1 , 3 ) + self.x.view(snake_case_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(snake_case_ , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=snake_case_ ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(snake_case_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(snake_case_ , *snake_case_ , 2 , 3 ) def UpperCamelCase__ ( self : List[str] , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=snake_case_ , height=snake_case_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> Any: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowerCAmelCase__ ), np.cos(lowerCAmelCase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowerCAmelCase__ ), -np.sin(lowerCAmelCase__ ), 0.0] ) _a = np.cross(lowerCAmelCase__ , lowerCAmelCase__ ) origins.append(lowerCAmelCase__ ) xs.append(lowerCAmelCase__ ) ys.append(lowerCAmelCase__ ) zs.append(lowerCAmelCase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowerCAmelCase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowerCAmelCase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowerCAmelCase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowerCAmelCase__ , axis=0 ) ).float() , width=lowerCAmelCase__ , height=lowerCAmelCase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowerCAmelCase__ )) , )
352
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : int = '▁' lowerCAmelCase_ : Optional[Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : Union[str, Any] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['input_ids', 'attention_mask'] __a =[] def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Any="<s>" , __a : List[str]="</s>" , __a : str="<pad>" , __a : List[str]="<unk>" , __a : Union[str, Any]=False , __a : Any=False , __a : List[str]=None , __a : Optional[int]=None , __a : Optional[Dict[str, Any]] = None , **__a : int , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = do_upper_case _a = do_lower_case _a = load_json(__a ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__a , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : str ): return len(self.encoder ) @property def UpperCamelCase__ ( self : str ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : Optional[int] , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : Dict , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : List[str] , __a : Any ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a , self.unk_token ) def UpperCamelCase__ ( self : str , __a : List[str] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__a ) _a = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : int , __a : Any , __a : int=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase__ ( self : Any , __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 ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): _a = Path(__a ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(lowercase , "r" ) as f: return json.load(lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> None: with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase , indent=2 )
346
0
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str , __a : Dict=3 , __a : str=32 , __a : Tuple=3 , __a : List[str]=10 , __a : str=[8, 16, 32, 64] , __a : Any=[1, 1, 2, 1] , __a : Tuple=True , __a : Optional[int]=True , __a : Any="relu" , __a : List[str]=3 , __a : int=None , __a : Dict=["stage2", "stage3", "stage4"] , __a : int=[2, 3, 4] , __a : int=1 , ): _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(__a ) _a = out_features _a = out_indices _a = num_groups def UpperCamelCase__ ( self : str ): _a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.num_labels ) _a = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( 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 UpperCamelCase__ ( self : str , __a : Tuple , __a : Tuple , __a : List[Any] ): _a = BitModel(config=__a ) model.to(__a ) model.eval() _a = model(__a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : Optional[Any] , __a : Tuple ): _a = self.num_labels _a = BitForImageClassification(__a ) model.to(__a ) model.eval() _a = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self : List[Any] , __a : Dict , __a : Dict , __a : Optional[int] ): _a = BitBackbone(config=__a ) model.to(__a ) model.eval() _a = model(__a ) # 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 _a = None _a = BitBackbone(config=__a ) model.to(__a ) model.eval() _a = model(__a ) # 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 UpperCamelCase__ ( self : Dict ): _a = self.prepare_config_and_inputs() _a , _a , _a = config_and_inputs _a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =(BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () __a =( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) __a =False __a =False __a =False __a =False __a =False def UpperCamelCase__ ( self : Tuple ): _a = BitModelTester(self ) _a = ConfigTester(self , config_class=__a , has_text_modality=__a ) def UpperCamelCase__ ( self : str ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase__ ( self : Any ): return @unittest.skip(reason="Bit does not output attentions" ) def UpperCamelCase__ ( self : Tuple ): pass @unittest.skip(reason="Bit does not use inputs_embeds" ) def UpperCamelCase__ ( self : Union[str, Any] ): pass @unittest.skip(reason="Bit does not support input and output embeddings" ) def UpperCamelCase__ ( self : Union[str, Any] ): pass def UpperCamelCase__ ( self : Dict ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__a ) _a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a = [*signature.parameters.keys()] _a = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def UpperCamelCase__ ( self : Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__a ) def UpperCamelCase__ ( self : Tuple ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(config=__a ) for name, module in model.named_modules(): if isinstance(__a , (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 UpperCamelCase__ ( self : List[Any] ): def check_hidden_states_output(__a : List[Any] , __a : Any , __a : Optional[Any] ): _a = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__a , __a ) ) _a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a = self.model_tester.num_stages self.assertEqual(len(__a ) , 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] , ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = ["preactivation", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: _a = layer_type _a = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a = True check_hidden_states_output(__a , __a , __a ) @unittest.skip(reason="Bit does not use feedforward chunking" ) def UpperCamelCase__ ( self : Dict ): pass def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def UpperCamelCase__ ( self : Dict ): for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = BitModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _lowerCamelCase ( ) -> str: _a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @cached_property def UpperCamelCase__ ( self : int ): return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self : List[Any] ): _a = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__a ) _a = self.default_image_processor _a = prepare_img() _a = image_processor(images=__a , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): _a = model(**__a ) # verify the logits _a = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __a ) _a = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) ) @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =(BitBackbone,) if is_torch_available() else () __a =BitConfig __a =False def UpperCamelCase__ ( self : List[str] ): _a = BitModelTester(self )
353
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): _a = Rectangle(height=0.5 , width=0.5 ) _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _a = [mem.copy() for i in range(6 )] _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(__a , __a ).arrange(__a , buff=0 ) _a = Text("CPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__a ) _a = [mem.copy() for i in range(4 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("GPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) gpu.move_to([-1, -1, 0] ) self.add(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Model" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) model.move_to([3, -1.0, 0] ) self.add(__a ) _a = [] for i, rect in enumerate(__a ): rect.set_stroke(__a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__a , buff=0.0 ) self.add(__a ) cpu_targs.append(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Loaded Checkpoint" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , aligned_edge=__a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) _a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _a = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__a , __a ) _a = MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) _a = MarkupText( f'Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__a ) , Write(__a ) ) self.play(Write(__a , run_time=1 ) , Create(__a , run_time=1 ) ) _a = [] _a = [] for i, rect in enumerate(__a ): _a = fill.copy().set_fill(__a , opacity=0.7 ) target.move_to(__a ) first_animations.append(GrowFromCenter(__a , run_time=1 ) ) _a = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__a , run_time=1.5 ) ) self.play(*__a ) self.play(*__a ) self.wait()
346
0
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase_ : Dict = {"vocab_file": "vocab.txt"} lowerCAmelCase_ : Tuple = { "vocab_file": { "openbmb/cpm-ant-10b": "https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt", }, } lowerCAmelCase_ : Union[str, Any] = { "openbmb/cpm-ant-10b": 10_24, } def _lowerCamelCase ( lowercase : Optional[int] ) -> Tuple: _a = collections.OrderedDict() with open(lowercase , "r" , encoding="utf-8" ) as reader: _a = reader.readlines() for index, token in enumerate(lowercase ): _a = token.rstrip("\n" ) _a = index return vocab class __SCREAMING_SNAKE_CASE (lowercase_ ): """simple docstring""" def __init__( self : Optional[int] , __a : Optional[int] , __a : Dict="<unk>" , __a : str=2_00 ): _a = vocab _a = unk_token _a = max_input_chars_per_word def UpperCamelCase__ ( self : Optional[int] , __a : List[str] ): _a = list(a__ ) if len(a__ ) > self.max_input_chars_per_word: return [self.unk_token] _a = 0 _a = [] while start < len(a__ ): _a = len(a__ ) _a = None while start < end: _a = "".join(chars[start:end] ) if substr in self.vocab: _a = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(a__ ) _a = end return sub_tokens class __SCREAMING_SNAKE_CASE (lowercase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a =["input_ids", "attention_mask"] __a =False def __init__( self : Optional[Any] , __a : str , __a : Optional[int]="<d>" , __a : List[str]="</d>" , __a : Dict="<s>" , __a : int="</s>" , __a : Tuple="<pad>" , __a : Optional[Any]="<unk>" , __a : Dict="</n>" , __a : Optional[int]="</_>" , __a : List[str]="left" , **__a : Optional[int] , ): requires_backends(self , ["jieba"] ) super().__init__( bod_token=a__ , eod_token=a__ , bos_token=a__ , eos_token=a__ , pad_token=a__ , unk_token=a__ , line_token=a__ , space_token=a__ , padding_side=a__ , **a__ , ) _a = bod_token _a = eod_token _a = load_vocab(a__ ) _a = self.encoder[space_token] _a = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] _a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __a : x[1] ) ) _a = {v: k for k, v in self.encoder.items()} _a = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def UpperCamelCase__ ( self : Tuple ): return self.encoder[self.bod_token] @property def UpperCamelCase__ ( self : Union[str, Any] ): return self.encoder[self.eod_token] @property def UpperCamelCase__ ( self : int ): return self.encoder["\n"] @property def UpperCamelCase__ ( self : List[str] ): return len(self.encoder ) def UpperCamelCase__ ( self : List[str] ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase__ ( self : int , __a : Optional[Any] ): _a = [] for x in jieba.cut(a__ , cut_all=a__ ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(a__ ) ) return output_tokens def UpperCamelCase__ ( self : Optional[int] , __a : Optional[int] , **__a : int ): _a = [i for i in token_ids if i >= 0] _a = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(a__ , **a__ ) def UpperCamelCase__ ( self : Any , __a : Any ): return token in self.encoder def UpperCamelCase__ ( self : Tuple , __a : List[str] ): return "".join(a__ ) def UpperCamelCase__ ( self : str , __a : int ): return self.encoder.get(a__ , self.encoder.get(self.unk_token ) ) def UpperCamelCase__ ( self : List[str] , __a : Union[str, Any] ): return self.decoder.get(a__ , self.unk_token ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : Tuple = None ): if os.path.isdir(a__ ): _a = os.path.join( a__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) else: _a = (filename_prefix + "-" if filename_prefix else "") + save_directory _a = 0 if " " in self.encoder: _a = self.encoder[" "] del self.encoder[" "] if "\n" in self.encoder: _a = self.encoder["\n"] del self.encoder["\n"] _a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __a : x[1] ) ) with open(a__ , "w" , encoding="utf-8" ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' " Please check that the vocabulary is not corrupted!" ) _a = token_index writer.write(token + "\n" ) index += 1 return (vocab_file,) def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : List[Any] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def UpperCamelCase__ ( self : str , __a : str , __a : List[str] = None , __a : Any = 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 not None: return [1] + ([0] * len(a__ )) + [1] + ([0] * len(a__ )) return [1] + ([0] * len(a__ ))
354
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase_ : Tuple = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = test_results.split(" " ) _a = 0 _a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _a = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = {} _a = None _a = False for line in failures_short_lines.split("\n" ): if re.search(r"_ \[doctest\]" , lowercase ): _a = True _a = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): _a = line _a = False return failures class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : str , __a : Dict ): _a = title _a = doc_test_results["time_spent"].split("," )[0] _a = doc_test_results["success"] _a = doc_test_results["failures"] _a = self.n_success + self.n_failures # Failures and success of the modeling tests _a = doc_test_results @property def UpperCamelCase__ ( self : int ): _a = [self._time_spent] _a = 0 for time in time_spent: _a = time.split(":" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__a ) == 1: _a = [0, 0, time_parts[0]] _a , _a , _a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds _a , _a , _a = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(__a )}h{int(__a )}m{int(__a )}s' @property def UpperCamelCase__ ( self : Optional[Any] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self : Optional[Any] ): return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : List[str] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : str ): _a = 40 _a = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__a , __a )} _a = "" for category, failures in category_failures.items(): if len(__a ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def UpperCamelCase__ ( self : List[str] ): _a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__a ) @staticmethod def UpperCamelCase__ ( ): _a = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(__a )} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=__a , ) def UpperCamelCase__ ( self : Tuple ): print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(self.payload )} ) ) _a = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else "All tests passed." _a = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=__a , ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : List[Any] , __a : Tuple , __a : int ): _a = "" for key, value in failures.items(): _a = value[:2_00] + " [Truncated]" if len(__a ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' _a = job_name _a = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: _a = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self : str ): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made." ) _a = self.doc_test_results.pop("job_link" ) self.doc_test_results.pop("failures" ) self.doc_test_results.pop("success" ) self.doc_test_results.pop("time_spent" ) _a = sorted(self.doc_test_results.items() , key=lambda __a : t[0] ) for job, job_result in sorted_dict: if len(job_result["failures"] ): _a = f'*Num failures* :{len(job_result["failed"] )} \n' _a = job_result["failures"] _a = self.get_reply_blocks(__a , __a , __a , text=__a ) print("Sending the following reply" ) print(json.dumps({"blocks": blocks} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=f'Results for {job}' , blocks=__a , thread_ts=self.thread_ts["ts"] , ) time.sleep(1 ) def _lowerCamelCase ( ) -> Any: _a = os.environ["GITHUB_RUN_ID"] _a = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _a = requests.get(lowercase ).json() _a = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) _a = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): _a = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , lowercase ) return {} def _lowerCamelCase ( lowercase : str ) -> Dict: _a = {} if os.path.exists(lowercase ): _a = os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase , lowercase ) , encoding="utf-8" ) as f: _a = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase , lowercase )}.' ) from e return _artifact def _lowerCamelCase ( ) -> str: class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str ): _a = name _a = [] def __str__( self : List[str] ): return self.name def UpperCamelCase__ ( self : str , __a : str ): self.paths.append({"name": self.name, "path": path} ) _a = {} _a = filter(os.path.isdir , os.listdir() ) for directory in directories: _a = directory if artifact_name not in _available_artifacts: _a = Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase_ : List[Any] = get_job_links() lowerCAmelCase_ : Any = retrieve_available_artifacts() lowerCAmelCase_ : List[str] = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase_ : Optional[Any] = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase_ : int = github_actions_job_links.get('run_doctests') lowerCAmelCase_ : Union[str, Any] = available_artifacts['doc_tests_gpu_test_reports'].paths[0] lowerCAmelCase_ : List[str] = retrieve_artifact(artifact_path['name']) if "stats" in artifact: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = handle_test_results(artifact['stats']) lowerCAmelCase_ : List[str] = failed lowerCAmelCase_ : Optional[Any] = success lowerCAmelCase_ : Tuple = time_spent[1:-1] + ', ' lowerCAmelCase_ : List[Any] = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): lowerCAmelCase_ : int = line.replace('FAILED ', '') lowerCAmelCase_ : Optional[int] = line.split()[0].replace('\n', '') if "::" in line: lowerCAmelCase_ , lowerCAmelCase_ : str = line.split('::') else: lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase_ : Union[str, Any] = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase_ : List[str] = all_failures[test] if test in all_failures else 'N/A' lowerCAmelCase_ : Optional[Any] = failure break lowerCAmelCase_ : Tuple = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase_ : Dict = {'tokenization_bertweet': ['BertweetTokenizer']} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys lowerCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
355
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCamelCase ( ) -> str: _a = HfArgumentParser(lowercase ) _a = parser.parse_args_into_dataclasses()[0] _a = TensorFlowBenchmark(args=lowercase ) try: _a = parser.parse_args_into_dataclasses()[0] except ValueError as e: _a = "Arg --no_{0} is no longer used, please use --no-{0} instead." _a = " ".join(str(lowercase ).split(" " )[:-1] ) _a = "" _a = eval(str(lowercase ).split(" " )[-1] ) _a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowercase ) if len(lowercase ) > 0: _a = full_error_msg + begin_error_msg + str(lowercase ) raise ValueError(lowercase ) benchmark.run() if __name__ == "__main__": main()
346
0
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase__ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='Pix2StructImageProcessor' __a =('T5Tokenizer', 'T5TokenizerFast') def __init__( self : int , __a : Optional[Any] , __a : Tuple ): _a = False super().__init__(__lowerCamelCase , __lowerCamelCase ) def __call__( self : Optional[Any] , __a : Optional[Any]=None , __a : List[Any] = None , __a : Optional[int] = True , __a : Optional[int] = False , __a : Any = None , __a : Any = None , __a : List[str] = 20_48 , __a : Tuple = 0 , __a : Dict = None , __a : Optional[int] = None , __a : int = False , __a : int = False , __a : Optional[Any] = False , __a : Tuple = False , __a : Optional[Any] = False , __a : Union[str, Any] = True , __a : List[str] = None , **__a : int , ): if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None and not self.image_processor.is_vqa: _a = self.tokenizer _a = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values _a = self.image_processor( __lowerCamelCase , return_tensors=__lowerCamelCase , max_patches=__lowerCamelCase , **__lowerCamelCase ) else: # add pixel_values and bbox _a = self.image_processor( __lowerCamelCase , return_tensors=__lowerCamelCase , max_patches=__lowerCamelCase , header_text=__lowerCamelCase , **__lowerCamelCase ) if text is not None and not self.image_processor.is_vqa: _a = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) if "attention_mask" in text_encoding: _a = text_encoding.pop("attention_mask" ) if "input_ids" in text_encoding: _a = text_encoding.pop("input_ids" ) else: _a = None if text_encoding is not None: encoding_image_processor.update(__lowerCamelCase ) return encoding_image_processor def UpperCamelCase__ ( self : Any , *__a : Union[str, Any] , **__a : List[str] ): return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase__ ( self : Optional[Any] , *__a : Optional[Any] , **__a : Union[str, Any] ): return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property def UpperCamelCase__ ( self : Dict ): _a = self.tokenizer.model_input_names _a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
356
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ : Union[str, Any] = None try: import msvcrt except ImportError: lowerCAmelCase_ : Tuple = None try: import fcntl except ImportError: lowerCAmelCase_ : Optional[int] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ : Any = OSError # Data # ------------------------------------------------ lowerCAmelCase_ : Tuple = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] lowerCAmelCase_ : Optional[int] = '3.0.12' lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( ) -> Optional[int]: global _logger _a = _logger or logging.getLogger(__name__ ) return _logger class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict , __a : Optional[Any] ): _a = lock_file return None def __str__( self : Any ): _a = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , __a : Optional[int] ): _a = lock return None def __enter__( self : str ): return self.lock def __exit__( self : List[Any] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): self.lock.release() return None class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] , __a : Optional[int]=-1 , __a : Tuple=None ): _a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long _a = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. _a = 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. _a = None # The default timeout value. _a = timeout # We use this lock primarily for the lock counter. _a = 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. _a = 0 return None @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file @property def UpperCamelCase__ ( self : List[Any] ): return self._timeout @timeout.setter def UpperCamelCase__ ( self : int , __a : List[Any] ): _a = float(__a ) return None def UpperCamelCase__ ( self : Dict ): raise NotImplementedError() def UpperCamelCase__ ( self : str ): raise NotImplementedError() @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file_fd is not None def UpperCamelCase__ ( self : int , __a : int=None , __a : Tuple=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: _a = 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 _a = id(self ) _a = self._lock_file _a = 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(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: _a = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: _a = id(self ) _a = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() _a = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : List[Any] ): self.acquire() return self def __exit__( self : str , __a : str , __a : Dict , __a : Dict ): self.release() return None def __del__( self : int ): self.release(force=__a ) return None def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): _a = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: _a = os.path.dirname(__a ) _a = str(hash(__a ) ) _a = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , __a : str , __a : List[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) _a = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def UpperCamelCase__ ( self : int ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Optional[Any] ): _a = self._lock_file_fd _a = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=-1 , __a : int=None ): _a = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def UpperCamelCase__ ( self : Any ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC _a = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Tuple ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition _a = self._lock_file_fd _a = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): _a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: _a = fd return None def UpperCamelCase__ ( self : Union[str, Any] ): os.close(self._lock_file_fd ) _a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ : str = None if msvcrt: lowerCAmelCase_ : List[str] = WindowsFileLock elif fcntl: lowerCAmelCase_ : List[str] = UnixFileLock else: lowerCAmelCase_ : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
346
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[str] , __a : Any , ): _a = parent _a = 13 _a = 7 _a = True _a = True _a = False _a = True _a = 99 _a = 32 _a = 2 _a = 4 _a = 37 _a = 'gelu' _a = 0.1 _a = 0.1 _a = 5_12 _a = 16 _a = 2 _a = 0.02 _a = 3 _a = 4 _a = None def UpperCamelCase__ ( self : int ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self : List[Any] , __a : Tuple , __a : int , __a : Any , __a : int , __a : List[str] , __a : str ): _a = TFDistilBertModel(config=_A ) _a = {'input_ids': input_ids, 'attention_mask': input_mask} _a = model(_A ) _a = [input_ids, input_mask] _a = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self : List[str] , __a : List[Any] , __a : Dict , __a : str , __a : List[Any] , __a : List[str] , __a : Optional[int] ): _a = TFDistilBertForMaskedLM(config=_A ) _a = {'input_ids': input_ids, 'attention_mask': input_mask} _a = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self : str , __a : int , __a : int , __a : Dict , __a : Union[str, Any] , __a : Optional[int] , __a : List[Any] ): _a = TFDistilBertForQuestionAnswering(config=_A ) _a = { 'input_ids': input_ids, 'attention_mask': input_mask, } _a = model(_A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self : List[Any] , __a : Any , __a : Tuple , __a : Dict , __a : Union[str, Any] , __a : Any , __a : List[str] ): _a = self.num_labels _a = TFDistilBertForSequenceClassification(_A ) _a = {'input_ids': input_ids, 'attention_mask': input_mask} _a = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self : Optional[int] , __a : List[Any] , __a : List[str] , __a : int , __a : Optional[Any] , __a : Optional[Any] , __a : int ): _a = self.num_choices _a = TFDistilBertForMultipleChoice(_A ) _a = tf.tile(tf.expand_dims(_A , 1 ) , (1, self.num_choices, 1) ) _a = tf.tile(tf.expand_dims(_A , 1 ) , (1, self.num_choices, 1) ) _a = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, } _a = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self : List[Any] , __a : str , __a : Any , __a : Optional[int] , __a : Tuple , __a : Dict , __a : Union[str, Any] ): _a = self.num_labels _a = TFDistilBertForTokenClassification(_A ) _a = {'input_ids': input_ids, 'attention_mask': input_mask} _a = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : Tuple ): _a = self.prepare_config_and_inputs() (_a) = config_and_inputs _a = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __a =( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __a =False __a =False def UpperCamelCase__ ( self : Optional[int] ): _a = TFDistilBertModelTester(self ) _a = ConfigTester(self , config_class=_A , dim=37 ) def UpperCamelCase__ ( self : Tuple ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : Optional[int] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*_A ) def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*_A ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*_A ) def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*_A ) def UpperCamelCase__ ( self : Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*_A ) def UpperCamelCase__ ( self : Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*_A ) @slow def UpperCamelCase__ ( self : Optional[int] ): for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): _a = TFDistilBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_tf class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : Optional[Any] ): _a = TFDistilBertModel.from_pretrained("distilbert-base-uncased" ) _a = tf.constant([[0, 1, 2, 3, 4, 5]] ) _a = model(_A )[0] _a = [1, 6, 7_68] self.assertEqual(output.shape , _A ) _a = tf.constant( [ [ [0.19261885, -0.13732955, 0.4119799], [0.22150156, -0.07422661, 0.39037204], [0.22756018, -0.0896414, 0.3701467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _A , atol=1e-4 )
357
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
0
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 __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : Dict , __a : List[Any]=13 , __a : List[Any]=7 , __a : Tuple=True , __a : Optional[Any]=True , __a : int=True , __a : Union[str, Any]=True , __a : str=99 , __a : Optional[int]=64 , __a : Any=32 , __a : Optional[int]=5 , __a : Union[str, Any]=4 , __a : List[str]=37 , __a : Optional[int]="gelu" , __a : Optional[Any]=0.1 , __a : List[str]=0.1 , __a : Any=5_12 , __a : Dict=16 , __a : List[str]=2 , __a : Optional[int]=0.02 , __a : int=3 , __a : int=4 , __a : Optional[Any]=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = embedding_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope def UpperCamelCase__ ( self : Any ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self : str ): 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=__snake_case , initializer_range=self.initializer_range , ) def UpperCamelCase__ ( self : Tuple , __a : List[Any] , __a : Optional[int] , __a : Optional[int] , __a : Union[str, Any] , __a : List[str] , __a : str , __a : int ): _a = MobileBertModel(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) _a = model(__snake_case , token_type_ids=__snake_case ) _a = model(__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 UpperCamelCase__ ( self : Dict , __a : str , __a : str , __a : Any , __a : str , __a : str , __a : Optional[int] , __a : Tuple ): _a = MobileBertForMaskedLM(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self : List[str] , __a : Union[str, Any] , __a : Optional[int] , __a : Optional[int] , __a : Optional[Any] , __a : Optional[int] , __a : List[str] , __a : List[Any] ): _a = MobileBertForNextSentencePrediction(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCamelCase__ ( self : str , __a : Any , __a : Union[str, Any] , __a : int , __a : List[Any] , __a : Optional[int] , __a : Optional[int] , __a : Optional[Any] ): _a = MobileBertForPreTraining(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , next_sentence_label=__snake_case , ) 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 UpperCamelCase__ ( self : Optional[Any] , __a : Tuple , __a : int , __a : Any , __a : List[str] , __a : Dict , __a : Dict , __a : Tuple ): _a = MobileBertForQuestionAnswering(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , start_positions=__snake_case , end_positions=__snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Optional[int] , __a : Union[str, Any] , __a : List[str] , __a : Optional[int] , __a : List[str] , __a : str ): _a = self.num_labels _a = MobileBertForSequenceClassification(__snake_case ) model.to(__snake_case ) model.eval() _a = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self : List[str] , __a : Dict , __a : Tuple , __a : Optional[Any] , __a : List[str] , __a : Tuple , __a : str , __a : Any ): _a = self.num_labels _a = MobileBertForTokenClassification(config=__snake_case ) model.to(__snake_case ) model.eval() _a = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : Optional[Any] , __a : List[str] , __a : int , __a : List[Any] , __a : Optional[int] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): _a = self.num_choices _a = MobileBertForMultipleChoice(config=__snake_case ) model.to(__snake_case ) model.eval() _a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.prepare_config_and_inputs() ( _a ) = config_and_inputs _a = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): """simple docstring""" __a =( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) __a =( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) __a =True def UpperCamelCase__ ( self : List[Any] , __a : Tuple , __a : Tuple , __a : Dict=False ): _a = super()._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) if return_labels: if model_class in get_values(__snake_case ): _a = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__snake_case ) _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__snake_case ) return inputs_dict def UpperCamelCase__ ( self : Optional[Any] ): _a = MobileBertModelTester(self ) _a = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def UpperCamelCase__ ( self : Union[str, Any] ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*__snake_case ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*__snake_case ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__snake_case ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__snake_case ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*__snake_case ) def UpperCamelCase__ ( self : int ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*__snake_case ) def UpperCamelCase__ ( self : str ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__snake_case ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*__snake_case ) def _lowerCamelCase ( lowercase : Any ) -> Union[str, Any]: return torch.tensor( _A , dtype=torch.long , device=_A , ) lowerCAmelCase_ : Tuple = 1e-3 @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : Any ): _a = MobileBertModel.from_pretrained("google/mobilebert-uncased" ).to(__snake_case ) _a = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): _a = model(__snake_case )[0] _a = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , __snake_case ) _a = torch.tensor( [ [ [-2.4_7_3_6_5_2_6e0_7, 8.2_6_9_1_6_5_6e0_4, 1.6_5_2_1_8_3_8e0_5], [-5.7_5_4_1_7_0_4e-0_1, 3.9_0_5_6_0_2_2e0_0, 4.4_0_1_1_5_0_7e0_0], [2.6_0_4_7_3_5_9e0_0, 1.5_6_7_7_6_5_2e0_0, -1.7_3_2_4_1_8_8e-0_1], ] ] , device=__snake_case , ) # 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 _a = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) _a = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
358
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ : List[str] = TypeVar('T') lowerCAmelCase_ : Dict = TypeVar('U') class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Union[str, Any] , __a : T | None , __a : U | None ): _a = key _a = val _a = None _a = None def __repr__( self : Any ): return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Dict ): _a = DoubleLinkedListNode(__a , __a ) _a = DoubleLinkedListNode(__a , __a ) _a , _a = self.rear, self.head def __repr__( self : str ): _a = ["DoubleLinkedList"] _a = self.head while node.next is not None: rep.append(str(__a ) ) _a = node.next rep.append(str(self.rear ) ) return ",\n ".join(__a ) def UpperCamelCase__ ( self : int , __a : DoubleLinkedListNode[T, U] ): _a = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _a = node _a = previous _a = node _a = self.rear def UpperCamelCase__ ( self : Any , __a : DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None _a = node.next _a = node.prev _a = None _a = None return node class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" __a ={} def __init__( self : Union[str, Any] , __a : int ): _a = DoubleLinkedList() _a = capacity _a = 0 _a = 0 _a = 0 _a = {} def __repr__( self : Optional[int] ): return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self : str , __a : T ): return key in self.cache def UpperCamelCase__ ( self : str , __a : T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _a = self.cache[key] _a = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__a ) return node.val self.miss += 1 return None def UpperCamelCase__ ( self : Tuple , __a : T , __a : U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _a = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _a = DoubleLinkedListNode(__a , __a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _a = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _a = value self.list.add(__a ) @classmethod def UpperCamelCase__ ( cls : Tuple , __a : int = 1_28 ): def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _a = LRUCache(__a ) _a = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _a = func(*__a ) cls.decorator_function_to_instance_map[func].put(args[0] , __a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__a , "cache_info" , __a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self : int , __a : Union[str, Any] , __a : Any , __a : Union[str, Any] , __a : Union[str, Any] , __a : Tuple , __a : Any , __a : Tuple , __a : Any , __a : Tuple , ): super().__init__() if safety_checker is None: logger.warning( f'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( speech_model=A__ , speech_processor=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , unet=A__ , scheduler=A__ , feature_extractor=A__ , ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Any = "auto" ): if slice_size == "auto": _a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A__ ) def UpperCamelCase__ ( self : List[Any] ): self.enable_attention_slicing(A__ ) @torch.no_grad() def __call__( self : Dict , __a : int , __a : Any=1_60_00 , __a : Tuple = 5_12 , __a : Tuple = 5_12 , __a : str = 50 , __a : Union[str, Any] = 7.5 , __a : Tuple = None , __a : Tuple = 1 , __a : Tuple = 0.0 , __a : List[Any] = None , __a : List[str] = None , __a : Tuple = "pil" , __a : Tuple = True , __a : Optional[Any] = None , __a : Optional[Any] = 1 , **__a : List[Any] , ): _a = self.speech_processor.feature_extractor( A__ , return_tensors="pt" , sampling_rate=A__ ).input_features.to(self.device ) _a = self.speech_model.generate(A__ , max_length=48_00_00 ) _a = self.speech_processor.tokenizer.batch_decode(A__ , skip_special_tokens=A__ , normalize=A__ )[ 0 ] if isinstance(A__ , A__ ): _a = 1 elif isinstance(A__ , A__ ): _a = len(A__ ) else: raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(A__ )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A__ , A__ ) or callback_steps <= 0) ): raise ValueError( f'`callback_steps` has to be a positive integer but is {callback_steps} of type' f' {type(A__ )}.' ) # get prompt text embeddings _a = self.tokenizer( A__ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) _a = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _a = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f' {self.tokenizer.model_max_length} tokens: {removed_text}' ) _a = text_input_ids[:, : self.tokenizer.model_max_length] _a = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method _a , _a , _a = text_embeddings.shape _a = text_embeddings.repeat(1 , A__ , 1 ) _a = text_embeddings.view(bs_embed * num_images_per_prompt , A__ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _a = 42 if negative_prompt is None: _a = [""] * batch_size elif type(A__ ) is not type(A__ ): raise TypeError( f'`negative_prompt` should be the same type to `prompt`, but got {type(A__ )} !=' f' {type(A__ )}.' ) elif isinstance(A__ , A__ ): _a = [negative_prompt] elif batch_size != len(A__ ): raise ValueError( f'`negative_prompt`: {negative_prompt} has batch size {len(A__ )}, but `prompt`:' f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' " the batch size of `prompt`." ) else: _a = negative_prompt _a = text_input_ids.shape[-1] _a = self.tokenizer( A__ , padding="max_length" , max_length=A__ , truncation=A__ , return_tensors="pt" , ) _a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _a = uncond_embeddings.shape[1] _a = uncond_embeddings.repeat(1 , A__ , 1 ) _a = uncond_embeddings.view(batch_size * num_images_per_prompt , A__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _a = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _a = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) _a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps _a = torch.randn(A__ , generator=A__ , device="cpu" , dtype=A__ ).to( self.device ) else: _a = torch.randn(A__ , generator=A__ , device=self.device , dtype=A__ ) else: if latents.shape != latents_shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) _a = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(A__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand _a = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _a = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _a = {} if accepts_eta: _a = eta for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance _a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _a = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual _a = self.unet(A__ , A__ , encoder_hidden_states=A__ ).sample # perform guidance if do_classifier_free_guidance: _a , _a = noise_pred.chunk(2 ) _a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 _a = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A__ , A__ , A__ ) _a = 1 / 0.18215 * latents _a = self.vae.decode(A__ ).sample _a = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _a = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _a = self.numpy_to_pil(A__ ) if not return_dict: return image return StableDiffusionPipelineOutput(images=A__ , nsfw_content_detected=A__ )
359
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowerCamelCase ( lowercase : str ) -> str: re.sub("<n>" , "" , lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowercase ) )
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Optional[int] ) -> int: return abs(lowercase ) if a == 0 else greatest_common_divisor(b % a , lowercase ) def _lowerCamelCase ( lowercase : Dict , lowercase : Dict ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. _a , _a = y, x % y return abs(lowercase ) def _lowerCamelCase ( ) -> int: try: _a = input("Enter two integers separated by comma (,): " ).split("," ) _a = int(nums[0] ) _a = int(nums[1] ) print( F'greatest_common_divisor({num_a}, {num_a}) = ' F'{greatest_common_divisor(lowercase , lowercase )}' ) print(F'By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(lowercase , lowercase )}' ) except (IndexError, UnboundLocalError, ValueError): print("Wrong input" ) if __name__ == "__main__": main()
360
'''simple docstring''' import requests lowerCAmelCase_ : List[Any] = 'YOUR API KEY' def _lowerCamelCase ( lowercase : str , lowercase : str = giphy_api_key ) -> list: _a = "+".join(query.split() ) _a = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' _a = requests.get(lowercase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
346
0
'''simple docstring''' from collections import Counter from timeit import timeit def _lowerCamelCase ( lowercase : str = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(" " , "" ).lower() ).values() ) < 2 def _lowerCamelCase ( lowercase : str = "" ) -> bool: if len(lowercase ) == 0: return True _a = input_str.replace(" " , "" ).lower() # character_freq_dict: Stores the frequency of every character in the input string _a = {} for character in lower_case_input_str: _a = character_freq_dict.get(lowercase , 0 ) + 1 _a = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def _lowerCamelCase ( lowercase : str = "" ) -> None: print("\nFor string = " , lowercase , ":" ) print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(lowercase ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(lowercase ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": lowerCAmelCase_ : Union[str, Any] = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) lowerCAmelCase_ : Any = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"""{check_str} can {'' if status else 'not '}be rearranged as a palindrome""")
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =BertGenerationTokenizer __a =False __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = BertGenerationTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ ( self : Tuple ): _a = "<s>" _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[str] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__a ) , 10_02 ) def UpperCamelCase__ ( self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def UpperCamelCase__ ( self : Tuple ): _a = BertGenerationTokenizer(__a , keep_accents=__a ) _a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [2_85, 46, 10, 1_70, 3_82] , ) _a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _a = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def UpperCamelCase__ ( self : Any ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def UpperCamelCase__ ( self : List[str] ): _a = "Hello World!" _a = [1_85_36, 22_60, 1_01] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def UpperCamelCase__ ( self : Optional[int] ): _a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def UpperCamelCase__ ( self : Tuple ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _a = list(self.big_tokenizer.get_vocab().keys() )[:10] _a = " ".join(__a ) _a = self.big_tokenizer.encode_plus(__a , return_tensors="pt" , return_token_type_ids=__a ) _a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__a ) _a = BertGenerationConfig() _a = BertGenerationEncoder(__a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def UpperCamelCase__ ( self : Optional[int] ): # fmt: off _a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ : str = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : str = [ '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_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
362
'''simple docstring''' def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Union[str, Any]: _enforce_args(lowercase , lowercase ) if n == 0: return 0 _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase ) ) return max_revue def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Tuple: _enforce_args(lowercase , lowercase ) _a = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase , lowercase , lowercase ) def _lowerCamelCase ( lowercase : int , lowercase : list , lowercase : list ) -> List[str]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase , lowercase ) , ) _a = max_revenue return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Any: _enforce_args(lowercase , lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _a = [float("-inf" ) for _ in range(n + 1 )] _a = 0 for i in range(1 , n + 1 ): _a = max_rev[i] for j in range(1 , i + 1 ): _a = max(lowercase , prices[j - 1] + max_rev[i - j] ) _a = max_revenue_i return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Dict: if n < 0: _a = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): _a = ( "Each integral piece of rod must have a corresponding price. " F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def _lowerCamelCase ( ) -> Any: _a = [6, 10, 12, 15, 20, 23] _a = len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _a = 36 _a = top_down_cut_rod(lowercase , lowercase ) _a = bottom_up_cut_rod(lowercase , lowercase ) _a = naive_cut_rod_recursive(lowercase , lowercase ) 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()
346
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE (_snake_case ): """simple docstring""" __a =['pixel_values'] def __init__( self : str , __a : List[str] = True , __a : int = None , __a : str = PILImageResampling.BICUBIC , __a : Optional[Any] = True , __a : Union[str, Any] = None , __a : int = True , __a : Tuple = 1 / 2_55 , __a : int = True , __a : Dict = None , __a : List[str] = None , __a : Optional[int] = True , **__a : List[Any] , ): super().__init__(**UpperCamelCase__ ) _a = size if size is not None else {"shortest_edge": 2_24} _a = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) _a = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} _a = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="crop_size" ) _a = do_resize _a = size _a = resample _a = do_center_crop _a = crop_size _a = do_rescale _a = rescale_factor _a = do_normalize _a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _a = image_std if image_std is not None else OPENAI_CLIP_STD _a = do_convert_rgb def UpperCamelCase__ ( self : List[Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : Union[str, Any] = PILImageResampling.BICUBIC , __a : Optional[Any] = None , **__a : Optional[int] , ): _a = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) _a = get_resize_output_image_size(UpperCamelCase__ , size=size["shortest_edge"] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[Any] , __a : List[str] , __a : Union[str, Any] = None , **__a : Any , ): _a = get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(UpperCamelCase__ , size=(size["height"], size["width"]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCamelCase__ ( self : Any , __a : Tuple , __a : Optional[Any] , __a : Tuple = None , **__a : Optional[Any] , ): return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCamelCase__ ( self : int , __a : Optional[Any] , __a : Tuple , __a : Union[str, Any] , __a : int = None , **__a : Optional[Any] , ): return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCamelCase__ ( self : Tuple , __a : Any , __a : Optional[Any] = None , __a : Dict = None , __a : Optional[int] = None , __a : str = None , __a : str = None , __a : Optional[Any] = None , __a : List[Any] = None , __a : List[str] = None , __a : List[str] = None , __a : Optional[Any] = None , __a : List[str] = None , __a : str = None , __a : Any = ChannelDimension.FIRST , **__a : Optional[Any] , ): _a = do_resize if do_resize is not None else self.do_resize _a = size if size is not None else self.size _a = get_size_dict(UpperCamelCase__ , param_name="size" , default_to_square=UpperCamelCase__ ) _a = resample if resample is not None else self.resample _a = do_center_crop if do_center_crop is not None else self.do_center_crop _a = crop_size if crop_size is not None else self.crop_size _a = get_size_dict(UpperCamelCase__ , param_name="crop_size" , default_to_square=UpperCamelCase__ ) _a = do_rescale if do_rescale is not None else self.do_rescale _a = rescale_factor if rescale_factor is not None else self.rescale_factor _a = do_normalize if do_normalize is not None else self.do_normalize _a = image_mean if image_mean is not None else self.image_mean _a = image_std if image_std is not None else self.image_std _a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _a = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: _a = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. _a = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: _a = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: _a = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: _a = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: _a = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] _a = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] _a = {"pixel_values": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
363
'''simple docstring''' 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_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , *__a : Optional[int] , **__a : List[str] ): super().__init__(*__a , **__a ) self.check_model_type(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : int=None , __a : Optional[Any]=None , **__a : List[Any] ): _a , _a = {}, {} if padding is not None: _a = padding if truncation is not None: _a = truncation if top_k is not None: _a = top_k return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __a : Union["Image.Image", str] , __a : str = None , **__a : Any ): if isinstance(__a , (Image.Image, str) ) and isinstance(__a , __a ): _a = {"image": image, "question": question} else: _a = image _a = super().__call__(__a , **__a ) return results def UpperCamelCase__ ( self : Tuple , __a : Tuple , __a : Optional[Any]=False , __a : List[Any]=False ): _a = load_image(inputs["image"] ) _a = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=__a , truncation=__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) model_inputs.update(__a ) return model_inputs def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.sigmoid()[0] _a , _a = probs.topk(__a ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
346
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 lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : Any = {'vocab_file': 'sentencepiece.bpe.model'} lowerCAmelCase_ : str = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } lowerCAmelCase_ : Optional[Any] = { 'camembert-base': 5_12, } lowerCAmelCase_ : Any = '▁' class __SCREAMING_SNAKE_CASE (snake_case__ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a =["""input_ids""", """attention_mask"""] def __init__( self : Any , __a : Any , __a : Dict="<s>" , __a : Tuple="</s>" , __a : int="</s>" , __a : List[str]="<s>" , __a : Dict="<unk>" , __a : Any="<pad>" , __a : List[Any]="<mask>" , __a : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , __a : List[str] = None , **__a : Optional[int] , ): _a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token _a = {} 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 , ) _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_A ) ) _a = 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> _a = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} _a = len(self.fairseq_tokens_to_ids ) _a = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _a = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase__ ( self : Optional[int] , __a : Union[str, Any] , __a : List[Any] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a = [self.cls_token_id] _a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase__ ( self : List[Any] , __a : List[str] , __a : Optional[int] = None , __a : str = 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 UpperCamelCase__ ( self : Optional[int] , __a : Any , __a : List[Any] = None ): _a = [self.sep_token_id] _a = [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 UpperCamelCase__ ( self : Any ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase__ ( self : List[str] , __a : Dict ): return self.sp_model.encode(_A , out_type=_A ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict ): 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 UpperCamelCase__ ( self : str , __a : str ): 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 UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): _a = [] _a = "" _a = 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 _a = True _a = [] else: current_sub_tokens.append(_A ) _a = False out_string += self.sp_model.decode(_A ) return out_string.strip() def __getstate__( self : int ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Optional[int] ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ ( self : Tuple , __a : Union[str, Any] , __a : Union[str, Any] = None ): if not os.path.isdir(_A ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _a = 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: _a = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,)
364
'''simple docstring''' from random import randint, random def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : bool = False , lowercase : int = 5 , ) -> list: _a = [[-1] * number_of_cells] # Create a highway without any car _a = 0 _a = max(lowercase , 0 ) while i < number_of_cells: _a = ( randint(0 , lowercase ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( lowercase : list , lowercase : int ) -> int: _a = 0 _a = highway_now[car_index + 1 :] for cell in range(len(lowercase ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(lowercase , -1 ) def _lowerCamelCase ( lowercase : list , lowercase : float , lowercase : int ) -> list: _a = len(lowercase ) # Beforce calculations, the highway is empty _a = [-1] * number_of_cells for car_index in range(lowercase ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _a = min(highway_now[car_index] + 1 , lowercase ) # Number of empty cell before the next car _a = get_distance(lowercase , lowercase ) - 1 # We can't have the car causing an accident _a = min(next_highway[car_index] , lowercase ) if random() < probability: # Randomly, a driver will slow down _a = max(next_highway[car_index] - 1 , 0 ) return next_highway def _lowerCamelCase ( lowercase : list , lowercase : int , lowercase : float , lowercase : int ) -> list: _a = len(highway[0] ) for i in range(lowercase ): _a = update(highway[i] , lowercase , lowercase ) _a = [-1] * number_of_cells for car_index in range(lowercase ): _a = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _a = (car_index + speed) % number_of_cells # Commit the change of position _a = speed highway.append(lowercase ) return highway if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def _lowerCamelCase ( lowercase : Tuple ) -> str: _a = image.size _a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 _a = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) _a = np.array(snake_case__ ).astype(np.floataa ) / 2_55.0 _a = image[None].transpose(0 , 3 , 1 , 2 ) _a = torch.from_numpy(snake_case__ ) return 2.0 * image - 1.0 class __SCREAMING_SNAKE_CASE (a__ ): """simple docstring""" def __init__( self : Optional[int] , __a : Tuple , __a : Tuple , __a : Optional[Any] , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self : Tuple , __a : List[Any] = None , __a : List[str] = 1 , __a : Any = 1_00 , __a : Optional[Any] = 0.0 , __a : List[Any] = None , __a : Union[str, Any] = "pil" , __a : Dict = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): _a = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): _a = image.shape[0] else: raise ValueError(f'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): _a = preprocess(SCREAMING_SNAKE_CASE_ ) _a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image _a = (batch_size, self.unet.config.in_channels // 2, height, width) _a = next(self.unet.parameters() ).dtype _a = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) _a = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) _a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler _a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _a = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _a = {} if accepts_eta: _a = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. _a = torch.cat([latents, image] , dim=1 ) _a = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual _a = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 _a = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE _a = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample _a = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) _a = image / 2 + 0.5 _a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _a = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
365
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
346
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def __init__( self : int , __a : int , __a : Tuple=7 , __a : List[str]=3 , __a : Union[str, Any]=18 , __a : Union[str, Any]=30 , __a : int=4_00 , __a : List[str]=True , __a : int=None , __a : Dict=True , ): _a = size if size is not None else {"height": 18, "width": 18} _a = parent _a = batch_size _a = num_channels _a = image_size _a = min_resolution _a = max_resolution _a = do_resize _a = size _a = apply_ocr def UpperCamelCase__ ( self : Union[str, Any] ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __SCREAMING_SNAKE_CASE (_SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __a =LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCamelCase__ ( self : Tuple ): _a = LayoutLMvaImageProcessingTester(self ) @property def UpperCamelCase__ ( self : Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self : Dict ): _a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , "do_resize" ) ) self.assertTrue(hasattr(__a , "size" ) ) self.assertTrue(hasattr(__a , "apply_ocr" ) ) def UpperCamelCase__ ( self : List[str] ): _a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) _a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def UpperCamelCase__ ( self : Any ): pass def UpperCamelCase__ ( self : Optional[int] ): # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched _a = 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, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase__ ( self : Optional[int] ): # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _a = 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 _a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched _a = 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, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase__ ( self : List[str] ): # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a = 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 _a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched _a = 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, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase__ ( self : List[str] ): # with apply_OCR = True _a = LayoutLMvaImageProcessor() from datasets import load_dataset _a = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) _a = Image.open(ds[0]["file"] ).convert("RGB" ) _a = image_processing(__a , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 _a = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 _a = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False _a = LayoutLMvaImageProcessor(apply_ocr=__a ) _a = image_processing(__a , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0
'''simple docstring''' from math import factorial lowerCAmelCase_ : Any = {str(d): factorial(d) for d in range(10)} def _lowerCamelCase ( lowercase : List[str] ) -> Dict: return sum(DIGIT_FACTORIAL[d] for d in str(lowercase ) ) def _lowerCamelCase ( ) -> Optional[int]: _a = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , lowercase ) if sum_of_digit_factorial(lowercase ) == i ) if __name__ == "__main__": print(f"""{solution() = }""")
367
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ : List[Any] = logging.getLogger(__name__) lowerCAmelCase_ : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowerCAmelCase_ : int = {'facebook/bart-base': BartTokenizer} def _lowerCamelCase ( ) -> Union[str, Any]: _a = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=lowercase , default=lowercase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=lowercase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowercase , default=lowercase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowercase , ) parser.add_argument( "--config_name" , type=lowercase , default=lowercase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowercase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowercase , default=lowercase , help="Where to store the final ONNX file." ) _a = parser.parse_args() return args def _lowerCamelCase ( lowercase : Any , lowercase : Tuple="cpu" ) -> Optional[Any]: _a = model_dict[model_name].from_pretrained(lowercase ).to(lowercase ) _a = tokenizer_dict[model_name].from_pretrained(lowercase ) if model_name in ["facebook/bart-base"]: _a = 0 _a = None _a = 0 return huggingface_model, tokenizer def _lowerCamelCase ( lowercase : List[str] , lowercase : Tuple , lowercase : int , lowercase : Any , lowercase : Dict ) -> Any: model.eval() _a = None _a = torch.jit.script(BARTBeamSearchGenerator(lowercase ) ) with torch.no_grad(): _a = "My friends are cool but they eat too many carbs." _a = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) _a = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowercase , max_length=lowercase , early_stopping=lowercase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowercase , ) logger.info("Model exported to {}".format(lowercase ) ) _a = remove_dup_initializers(os.path.abspath(lowercase ) ) logger.info("Deduplicated and optimized model written to {}".format(lowercase ) ) _a = onnxruntime.InferenceSession(lowercase ) _a = ort_sess.run( lowercase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowercase ), "max_length": np.array(lowercase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def _lowerCamelCase ( ) -> Any: _a = parse_args() _a = 5 _a = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _a = torch.device(args.device ) _a , _a = load_model_tokenizer(args.model_name_or_path , lowercase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(lowercase ) if args.max_length: _a = args.max_length if args.num_beams: _a = args.num_beams if args.output_file_path: _a = args.output_file_path else: _a = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(lowercase , lowercase , lowercase , lowercase , lowercase ) if __name__ == "__main__": main()
346
0
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline lowerCAmelCase_ : List[str] = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": lowerCAmelCase_ : Any = 'hopper-medium-v2' lowerCAmelCase_ : Optional[int] = gym.make(env_name) lowerCAmelCase_ : Tuple = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) lowerCAmelCase_ : Optional[Any] = env.reset() lowerCAmelCase_ : List[str] = 0 lowerCAmelCase_ : Tuple = 0 lowerCAmelCase_ : Any = 10_00 lowerCAmelCase_ : Optional[int] = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy lowerCAmelCase_ : Any = pipeline(obs, planning_horizon=32) # execute action in environment lowerCAmelCase_ : Union[str, Any] = env.step(denorm_actions) lowerCAmelCase_ : Optional[int] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f"""Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:""" f""" {total_score}""" ) # save observations for rendering rollout.append(next_observation.copy()) lowerCAmelCase_ : Dict = next_observation except KeyboardInterrupt: pass print(f"""Total reward: {total_reward}""")
368
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCAmelCase_ : Dict = abspath(join(dirname(dirname(dirname(__file__))), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _lowerCamelCase ( lowercase : str ) -> Optional[int]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase ) def _lowerCamelCase ( lowercase : Dict ) -> str: from transformers.testing_utils import pytest_terminal_summary_main _a = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(lowercase , id=lowercase )
346
0
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker lowerCAmelCase_ : List[str] = 'CompVis/stable-diffusion-v1-1' lowerCAmelCase_ : Any = 'CompVis/stable-diffusion-v1-2' lowerCAmelCase_ : Tuple = 'CompVis/stable-diffusion-v1-3' lowerCAmelCase_ : Union[str, Any] = 'CompVis/stable-diffusion-v1-4' class __SCREAMING_SNAKE_CASE (_UpperCamelCase ): """simple docstring""" def __init__( self : Optional[Any] , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , __a : bool = True , ): super()._init_() _a = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _a = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _a = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _a = StableDiffusionPipeline( vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , requires_safety_checker=_UpperCAmelCase , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCamelCase__ ( self : Optional[int] ): return {k: getattr(self , _UpperCAmelCase ) for k in self.config.keys() if not k.startswith("_" )} def UpperCamelCase__ ( self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_UpperCAmelCase ) def UpperCamelCase__ ( self : str ): self.enable_attention_slicing(_UpperCAmelCase ) @torch.no_grad() def UpperCamelCase__ ( self : Any , __a : Union[str, List[str]] , __a : int = 5_12 , __a : int = 5_12 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : List[str] , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def UpperCamelCase__ ( self : str , __a : Union[str, List[str]] , __a : int = 5_12 , __a : int = 5_12 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Any , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def UpperCamelCase__ ( self : Dict , __a : Union[str, List[str]] , __a : int = 5_12 , __a : int = 5_12 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Union[str, Any] , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def UpperCamelCase__ ( self : Dict , __a : Union[str, List[str]] , __a : int = 5_12 , __a : int = 5_12 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def UpperCamelCase__ ( self : Union[str, Any] , __a : Union[str, List[str]] , __a : int = 5_12 , __a : int = 5_12 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Union[str, Any] , ): _a = 'cuda' if torch.cuda.is_available() else 'cpu' self.to(_UpperCAmelCase ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f'`height` and `width` must be divisible by 8 but are {height} and {width}.' ) # Get first result from Stable Diffusion Checkpoint v1.1 _a = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.2 _a = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.3 _a = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.4 _a = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
369
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @register_to_config def __init__( self : List[Any] , __a : int , __a : int , __a : int , __a : float , __a : int , __a : int , __a : int , __a : int , __a : str , __a : bool = False , ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.Embedding(__a , __a ) _a = False _a = nn.Dropout(p=__a ) _a = TaConfig( vocab_size=__a , d_model=__a , num_heads=__a , d_kv=__a , d_ff=__a , dropout_rate=__a , feed_forward_proj=__a , is_decoder=__a , is_encoder_decoder=__a , ) _a = nn.ModuleList() for lyr_num in range(__a ): _a = TaBlock(__a ) self.encoders.append(__a ) _a = TaLayerNorm(__a ) _a = nn.Dropout(p=__a ) def UpperCamelCase__ ( self : str , __a : Union[str, Any] , __a : Dict ): _a = self.token_embedder(__a ) _a = encoder_input_tokens.shape[1] _a = torch.arange(__a , device=encoder_input_tokens.device ) x += self.position_encoding(__a ) _a = self.dropout_pre(__a ) # inverted the attention mask _a = encoder_input_tokens.size() _a = self.get_extended_attention_mask(__a , __a ) for lyr in self.encoders: _a = lyr(__a , __a )[0] _a = self.layer_norm(__a ) return self.dropout_post(__a ), encoder_inputs_mask
346
0
'''simple docstring''' from __future__ import annotations lowerCAmelCase_ : Dict = '#' class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Any ): _a = {} def UpperCamelCase__ ( self : int , __a : str ): _a = self._trie for char in text: if char not in trie: _a = {} _a = trie[char] _a = True def UpperCamelCase__ ( self : List[str] , __a : str ): _a = self._trie for char in prefix: if char in trie: _a = trie[char] else: return [] return self._elements(UpperCamelCase__ ) def UpperCamelCase__ ( self : Any , __a : dict ): _a = [] for c, v in d.items(): _a = [" "] if c == END else [(c + s) for s in self._elements(UpperCamelCase__ )] result.extend(UpperCamelCase__ ) return tuple(UpperCamelCase__ ) lowerCAmelCase_ : Optional[int] = Trie() lowerCAmelCase_ : Optional[Any] = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _lowerCamelCase ( lowercase : List[Any] ) -> tuple: _a = trie.find_word(__SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def _lowerCamelCase ( ) -> None: print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
370
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Any: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : List[str] = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Union[str, Any]: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": _a = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Dict , lowercase : Dict ) -> str: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Tuple , __a : Optional[int] , __a : Any ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Tuple , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Dict=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : List[Any] , __a : Dict ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Union[str, Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Optional[int] , __a : pl.Trainer , __a : str ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ : Dict = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[Any] = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Optional[Any] = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Optional[Any] = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys lowerCAmelCase_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
371
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): lowerCAmelCase_ : str = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ : Union[str, Any] = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = (images / 2 + 0.5).clamp(0 , 1 ) _a = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _a = numpy_to_pil(lowercase ) return images def _lowerCamelCase ( lowercase : int ) -> List[Any]: if images.ndim == 3: _a = images[None, ...] _a = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _a = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: _a = [Image.fromarray(lowercase ) for image in images] return pil_images
346
0
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(DPMSolverSDEScheduler,) __a =10 def UpperCamelCase__ ( self : Tuple , **__a : Any ): _a = { "num_train_timesteps": 11_00, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**__a ) return config def UpperCamelCase__ ( self : Dict ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : str ): for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def UpperCamelCase__ ( self : Dict ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a ) def UpperCamelCase__ ( self : Optional[int] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma _a = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): _a = scheduler.scale_model_input(__a , __a ) _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a ) _a = output.prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1e-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1e-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def UpperCamelCase__ ( self : Any ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config(prediction_type="v_prediction" ) _a = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma _a = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): _a = scheduler.scale_model_input(__a , __a ) _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a ) _a = output.prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1e-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1e-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1e-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) _a = self.dummy_model() _a = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _a = scheduler.scale_model_input(__a , __a ) _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a ) _a = output.prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1e-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1e-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def UpperCamelCase__ ( self : Optional[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a , use_karras_sigmas=__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) _a = self.dummy_model() _a = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma _a = sample.to(__a ) for t in scheduler.timesteps: _a = scheduler.scale_model_input(__a , __a ) _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a ) _a = output.prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2
350
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: _a = 10 _a = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) _a = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(lowercase ) ), } , features=lowercase , ) return dataset @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=lowercase ) return filename # FILE_CONTENT + files lowerCAmelCase_ : Union[str, Any] = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = tmp_path_factory.mktemp("data" ) / "file.txt" _a = FILE_CONTENT with open(lowercase , "w" ) as f: f.write(lowercase ) return filename @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: import bza _a = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" _a = bytes(lowercase , "utf-8" ) with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Optional[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) _a = bytes(lowercase , "utf-8" ) with gzip.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Union[str, Any]: if datasets.config.LZ4_AVAILABLE: import lza.frame _a = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" _a = bytes(lowercase , "utf-8" ) with lza.frame.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Tuple ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _a = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(lowercase , "w" ) as archive: archive.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[Any] ) -> Dict: import tarfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any ) -> Union[str, Any]: import lzma _a = tmp_path_factory.mktemp("data" ) / "file.txt.xz" _a = bytes(lowercase , "utf-8" ) with lzma.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int , lowercase : Any ) -> Union[str, Any]: import zipfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> List[str]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _a = tmp_path_factory.mktemp("data" ) / "file.txt.zst" _a = bytes(lowercase , "utf-8" ) with zstd.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "file.xml" _a = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(lowercase , "w" ) as f: f.write(lowercase ) return filename lowerCAmelCase_ : Optional[int] = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] lowerCAmelCase_ : Dict = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } lowerCAmelCase_ : Dict = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> str: _a = datasets.Dataset.from_dict(lowercase ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> Dict: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(lowercase ) ) as con: _a = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> int: import bza _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(lowercase , "rb" ) as f: _a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Any , lowercase : Any ) -> List[str]: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Any , lowercase : List[Any] ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(lowercase , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Optional[Any] , lowercase : int ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) _a = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(lowercase , "wb" ) as f: _a = pq.ParquetWriter(lowercase , schema=lowercase ) _a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase ) )] for k in DATA[0]} , schema=lowercase ) writer.write_table(lowercase ) writer.close() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA_DICT_OF_LISTS} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> List[str]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_312: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> int: _a = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_STR: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Tuple: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : List[Any] ) -> List[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[Any] , lowercase : int ) -> str: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : int , lowercase : List[Any] ) -> Optional[int]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] , lowercase : str ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : Any , lowercase : Optional[int] ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str , lowercase : List[str] , lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> str: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Dict: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Dict: _a = ["0", "1", "2", "3"] _a = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Union[str, Any] , lowercase : Any ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : List[str] , lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int , lowercase : str ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename("unsupported.ext" ) ) f.write(lowercase , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Any: _a = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(lowercase , "w" , encoding="utf-8" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[Any]: return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: _a = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : Dict ) -> List[str]: if not head: return True # split the list to two parts _a , _a = head.next, head while fast and fast.next: _a = fast.next.next _a = slow.next _a = slow.next _a = None # Don't forget here! But forget still works! # reverse the second part _a = None while second: _a = second.next _a = node _a = second _a = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False _a = node.next _a = head.next return True def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Optional[Any]: if not head or not head.next: return True # 1. Get the midpoint (slow) _a = _a = _a = head while fast and fast.next: _a , _a = fast.next.next, slow.next # 2. Push the second half into the stack _a = [slow.val] while slow.next: _a = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False _a = cur.next return True def _lowerCamelCase ( lowercase : Optional[int] ) -> Any: if not head or not head.next: return True _a = {} _a = 0 while head: if head.val in d: d[head.val].append(lowercase ) else: _a = [pos] _a = head.next pos += 1 _a = pos - 1 _a = 0 for v in d.values(): if len(lowercase ) % 2 != 0: middle += 1 else: _a = 0 for i in range(0 , len(lowercase ) ): if v[i] + v[len(lowercase ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
351
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='LayoutLMv2ImageProcessor' __a =('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Dict , __a : int=None , __a : List[Any]=None , **__a : str ): if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self : Optional[int] , __a : Optional[Any] , __a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __a : Union[List[List[int]], List[List[List[int]]]] = None , __a : Optional[Union[List[int], List[List[int]]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = None , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Optional[Any] , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor _a = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): _a = [text] # add batch dimension (as the image processor always adds a batch dimension) _a = features["words"] _a = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values _a = features.pop("pixel_values" ) if return_overflowing_tokens is True: _a = self.get_overflowing_images(__a , encoded_inputs["overflow_to_sample_mapping"] ) _a = images return encoded_inputs def UpperCamelCase__ ( self : int , __a : List[Any] , __a : int ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(__a )} and {len(__a )}' ) return images_with_overflow def UpperCamelCase__ ( self : Optional[Any] , *__a : Dict , **__a : Union[str, Any] ): return self.tokenizer.batch_decode(*__a , **__a ) def UpperCamelCase__ ( self : Union[str, Any] , *__a : Optional[int] , **__a : Optional[Any] ): return self.tokenizer.decode(*__a , **__a ) @property def UpperCamelCase__ ( self : int ): return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase__ ( self : List[Any] ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , ) return self.image_processor_class @property def UpperCamelCase__ ( self : int ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , ) return self.image_processor
346
0
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCAmelCase_ : Dict = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =PegasusConfig __a ={} __a ='gelu' def __init__( self : Optional[int] , __a : List[str] , __a : Optional[Any]=13 , __a : List[Any]=7 , __a : int=True , __a : List[Any]=False , __a : Optional[int]=99 , __a : Optional[Any]=32 , __a : Optional[Any]=5 , __a : Union[str, Any]=4 , __a : Dict=37 , __a : Optional[Any]=0.1 , __a : List[str]=0.1 , __a : Union[str, Any]=20 , __a : List[Any]=2 , __a : Optional[Any]=1 , __a : List[Any]=0 , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = eos_token_id _a = pad_token_id _a = bos_token_id def UpperCamelCase__ ( self : Optional[Any] ): _a = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) _a = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) _a = np.concatenate([input_ids, eos_tensor] , axis=1 ) _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _a = prepare_pegasus_inputs_dict(__a , __a , __a ) return config, inputs_dict def UpperCamelCase__ ( self : Optional[int] , __a : int , __a : str , __a : Tuple ): _a = 20 _a = model_class_name(__a ) _a = model.encode(inputs_dict["input_ids"] ) _a , _a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _a = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) _a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) _a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) _a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) _a = model.decode( decoder_input_ids[:, -1:] , __a , decoder_attention_mask=__a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__a , ) _a = model.decode(__a , __a ) _a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def UpperCamelCase__ ( self : List[str] , __a : int , __a : Optional[Any] , __a : Any ): _a = 20 _a = model_class_name(__a ) _a = model.encode(inputs_dict["input_ids"] ) _a , _a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) _a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _a = model.init_cache(decoder_input_ids.shape[0] , __a , __a ) _a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a = model.decode( decoder_input_ids[:, :-1] , __a , decoder_attention_mask=__a , past_key_values=__a , decoder_position_ids=__a , ) _a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) _a = model.decode( decoder_input_ids[:, -1:] , __a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__a , decoder_position_ids=__a , ) _a = model.decode(__a , __a , decoder_attention_mask=__a ) _a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Optional[Any] , lowercase : Tuple , lowercase : Tuple=None , lowercase : List[str]=None , ) -> Dict: if attention_mask is None: _a = np.not_equal(lowercase , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: _a = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __a =(FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __a =True __a =False __a =False __a =False def UpperCamelCase__ ( self : Tuple ): _a = FlaxPegasusModelTester(self ) _a = ConfigTester(self , config_class=__a ) def UpperCamelCase__ ( self : Tuple ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : Dict ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__a , __a , __a ) def UpperCamelCase__ ( self : int ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__a , __a , __a ) def UpperCamelCase__ ( self : str ): _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(__a , __a ) _a = model_class(__a ) @jax.jit def encode_jitted(__a : Union[str, Any] , __a : Any=None , **__a : Any ): return model.encode(input_ids=__a , attention_mask=__a ) with self.subTest("JIT Enabled" ): _a = encode_jitted(**__a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): _a = encode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase__ ( self : Union[str, Any] ): _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 = model_class(__a ) _a = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) _a = { "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(__a : Union[str, Any] , __a : List[Any] , __a : str ): return model.decode( decoder_input_ids=__a , decoder_attention_mask=__a , encoder_outputs=__a , ) with self.subTest("JIT Enabled" ): _a = decode_jitted(**__a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): _a = decode_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase__ ( self : Optional[int] ): for model_class_name in self.all_model_classes: _a = model_class_name.from_pretrained("google/pegasus-large" , from_pt=__a ) _a = np.ones((1, 1) ) _a = model(__a ) self.assertIsNotNone(__a ) @slow def UpperCamelCase__ ( self : Optional[Any] ): _a = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) _a = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) _a = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] _a = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] _a = tokenizer(__a , return_tensors="np" , truncation=__a , max_length=5_12 , padding=__a ) _a = model.generate(**__a , num_beams=2 ).sequences _a = tokenizer.batch_decode(__a , skip_special_tokens=__a ) assert tgt_text == decoded
352
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : int = '▁' lowerCAmelCase_ : Optional[Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : Union[str, Any] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['input_ids', 'attention_mask'] __a =[] def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Any="<s>" , __a : List[str]="</s>" , __a : str="<pad>" , __a : List[str]="<unk>" , __a : Union[str, Any]=False , __a : Any=False , __a : List[str]=None , __a : Optional[int]=None , __a : Optional[Dict[str, Any]] = None , **__a : int , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = do_upper_case _a = do_lower_case _a = load_json(__a ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__a , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : str ): return len(self.encoder ) @property def UpperCamelCase__ ( self : str ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : Optional[int] , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : Dict , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : List[str] , __a : Any ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a , self.unk_token ) def UpperCamelCase__ ( self : str , __a : List[str] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__a ) _a = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : int , __a : Any , __a : int=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase__ ( self : Any , __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 ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): _a = Path(__a ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(lowercase , "r" ) as f: return json.load(lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> None: with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase , indent=2 )
346
0
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow lowerCAmelCase_ : Union[str, Any] = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] , __a : Path , __a : Union[str, None] = None , __a : Union[List[str], None] = None , __a : Union[str, List[str], None] = None , __a : bool = True , ): _a = [file for file in os.listdir(__a ) if os.path.isfile(os.path.join(__a , __a ) )] if identifier is not None: _a = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(__a , __a ): for n_ in n_identifier: _a = [file for file in files if n_ not in file] else: _a = [file for file in files if n_identifier not in file] _a = ignore_files or [] ignore_files.append("__init__.py" ) _a = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , __a ) if only_modules: _a = file.split("." )[0] try: _a = getattr(__a , __a ) _a = doctest.DocTestSuite(__a ) _a = unittest.TextTestRunner().run(__a ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'{module_identifier} is not a module.' ) else: _a = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def UpperCamelCase__ ( self : Optional[Any] ): _a = Path("src/transformers" ) _a = "modeling" _a = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(__a , identifier=__a , ignore_files=__a ) def UpperCamelCase__ ( self : str ): _a = Path("src/transformers" ) _a = "tokenization" self.analyze_directory(__a , identifier=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = Path("src/transformers" ) _a = "configuration" self.analyze_directory(__a , identifier=__a ) def UpperCamelCase__ ( self : Optional[Any] ): _a = Path("src/transformers" ) _a = ["configuration", "modeling", "tokenization"] self.analyze_directory(__a , n_identifier=__a ) def UpperCamelCase__ ( self : List[Any] ): _a = Path("docs/source" ) _a = ["favicon.ico"] self.analyze_directory(__a , ignore_files=__a , only_modules=__a )
353
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): _a = Rectangle(height=0.5 , width=0.5 ) _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _a = [mem.copy() for i in range(6 )] _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(__a , __a ).arrange(__a , buff=0 ) _a = Text("CPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__a ) _a = [mem.copy() for i in range(4 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("GPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) gpu.move_to([-1, -1, 0] ) self.add(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Model" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) model.move_to([3, -1.0, 0] ) self.add(__a ) _a = [] for i, rect in enumerate(__a ): rect.set_stroke(__a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__a , buff=0.0 ) self.add(__a ) cpu_targs.append(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Loaded Checkpoint" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , aligned_edge=__a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) _a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _a = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__a , __a ) _a = MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) _a = MarkupText( f'Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__a ) , Write(__a ) ) self.play(Write(__a , run_time=1 ) , Create(__a , run_time=1 ) ) _a = [] _a = [] for i, rect in enumerate(__a ): _a = fill.copy().set_fill(__a , opacity=0.7 ) target.move_to(__a ) first_animations.append(GrowFromCenter(__a , run_time=1 ) ) _a = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__a , run_time=1.5 ) ) self.play(*__a ) self.play(*__a ) self.wait()
346
0
'''simple docstring''' import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (enum.Enum ): """simple docstring""" __a =0 __a =1 @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='generated' def __init__( self : List[str] , *__a : Union[str, Any] , **__a : str ): super().__init__(*__a , **__a ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCamelCase__ ( self : int , __a : Optional[int]=None , __a : List[Any]=None , __a : Any=None , __a : Union[str, Any]=None , __a : Dict=None , __a : Union[str, Any]=None , **__a : Any , ): _a = {} if truncation is not None: _a = truncation _a = generate_kwargs _a = {} if return_tensors is not None and return_type is None: _a = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: _a = return_type if clean_up_tokenization_spaces is not None: _a = clean_up_tokenization_spaces if stop_sequence is not None: _a = self.tokenizer.encode(__a , add_special_tokens=__a ) if len(__a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) _a = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase__ ( self : str , __a : int , __a : int , __a : int ): return True def UpperCamelCase__ ( self : Any , *__a : Optional[int] , __a : Dict ): _a = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , __a ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) _a = ([prefix + arg for arg in args[0]],) _a = True elif isinstance(args[0] , __a ): _a = (prefix + args[0],) _a = False else: raise ValueError( f' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`' ) _a = self.tokenizer(*__a , padding=__a , truncation=__a , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : Dict , *__a : List[str] , **__a : Optional[Any] ): _a = super().__call__(*__a , **__a ) if ( isinstance(args[0] , __a ) and all(isinstance(__a , __a ) for el in args[0] ) and all(len(__a ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCamelCase__ ( self : Tuple , __a : Union[str, Any] , __a : List[str]=TruncationStrategy.DO_NOT_TRUNCATE , **__a : Optional[int] ): _a = self._parse_and_tokenize(__a , truncation=__a , **__a ) return inputs def UpperCamelCase__ ( self : int , __a : str , **__a : Optional[Any] ): if self.framework == "pt": _a , _a = model_inputs["input_ids"].shape elif self.framework == "tf": _a , _a = tf.shape(model_inputs["input_ids"] ).numpy() _a = generate_kwargs.get("min_length" , self.model.config.min_length ) _a = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(__a , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) _a = self.model.generate(**__a , **__a ) _a = output_ids.shape[0] if self.framework == "pt": _a = output_ids.reshape(__a , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": _a = tf.reshape(__a , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=ReturnType.TEXT , __a : Union[str, Any]=False ): _a = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: _a = {f'{self.return_name}_token_ids': output_ids} elif return_type == ReturnType.TEXT: _a = { f'{self.return_name}_text': self.tokenizer.decode( __a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a , ) } records.append(__a ) return records @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='summary' def __call__( self : List[Any] , *__a : Tuple , **__a : Tuple ): return super().__call__(*__a , **__a ) def UpperCamelCase__ ( self : List[str] , __a : int , __a : int , __a : int ): if max_length < min_length: logger.warning(f'Your min_length={min_length} must be inferior than your max_length={max_length}.' ) if input_length < max_length: logger.warning( f'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is ' "a summarization task, where outputs shorter than the input are typically wanted, you might " f'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})' ) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='translation' def UpperCamelCase__ ( self : Any , __a : int , __a : int , __a : int ): if input_length > 0.9 * max_length: logger.warning( f'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider ' "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCamelCase__ ( self : str , *__a : List[str] , __a : Dict=TruncationStrategy.DO_NOT_TRUNCATE , __a : Optional[int]=None , __a : Tuple=None ): if getattr(self.tokenizer , "_build_translation_inputs" , __a ): return self.tokenizer._build_translation_inputs( *__a , return_tensors=self.framework , truncation=__a , src_lang=__a , tgt_lang=__a ) else: return super()._parse_and_tokenize(*__a , truncation=__a ) def UpperCamelCase__ ( self : Any , __a : Optional[Any]=None , __a : Tuple=None , **__a : Tuple ): _a , _a , _a = super()._sanitize_parameters(**__a ) if src_lang is not None: _a = src_lang if tgt_lang is not None: _a = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. _a = kwargs.get("task" , self.task ) _a = task.split("_" ) if task and len(__a ) == 4: # translation, XX, to YY _a = items[1] _a = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : List[Any] , *__a : int , **__a : Any ): return super().__call__(*__a , **__a )
354
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase_ : Tuple = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = test_results.split(" " ) _a = 0 _a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _a = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = {} _a = None _a = False for line in failures_short_lines.split("\n" ): if re.search(r"_ \[doctest\]" , lowercase ): _a = True _a = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): _a = line _a = False return failures class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : str , __a : Dict ): _a = title _a = doc_test_results["time_spent"].split("," )[0] _a = doc_test_results["success"] _a = doc_test_results["failures"] _a = self.n_success + self.n_failures # Failures and success of the modeling tests _a = doc_test_results @property def UpperCamelCase__ ( self : int ): _a = [self._time_spent] _a = 0 for time in time_spent: _a = time.split(":" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__a ) == 1: _a = [0, 0, time_parts[0]] _a , _a , _a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds _a , _a , _a = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(__a )}h{int(__a )}m{int(__a )}s' @property def UpperCamelCase__ ( self : Optional[Any] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self : Optional[Any] ): return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : List[str] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : str ): _a = 40 _a = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__a , __a )} _a = "" for category, failures in category_failures.items(): if len(__a ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def UpperCamelCase__ ( self : List[str] ): _a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__a ) @staticmethod def UpperCamelCase__ ( ): _a = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(__a )} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=__a , ) def UpperCamelCase__ ( self : Tuple ): print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(self.payload )} ) ) _a = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else "All tests passed." _a = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=__a , ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : List[Any] , __a : Tuple , __a : int ): _a = "" for key, value in failures.items(): _a = value[:2_00] + " [Truncated]" if len(__a ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' _a = job_name _a = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: _a = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self : str ): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made." ) _a = self.doc_test_results.pop("job_link" ) self.doc_test_results.pop("failures" ) self.doc_test_results.pop("success" ) self.doc_test_results.pop("time_spent" ) _a = sorted(self.doc_test_results.items() , key=lambda __a : t[0] ) for job, job_result in sorted_dict: if len(job_result["failures"] ): _a = f'*Num failures* :{len(job_result["failed"] )} \n' _a = job_result["failures"] _a = self.get_reply_blocks(__a , __a , __a , text=__a ) print("Sending the following reply" ) print(json.dumps({"blocks": blocks} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=f'Results for {job}' , blocks=__a , thread_ts=self.thread_ts["ts"] , ) time.sleep(1 ) def _lowerCamelCase ( ) -> Any: _a = os.environ["GITHUB_RUN_ID"] _a = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _a = requests.get(lowercase ).json() _a = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) _a = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): _a = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , lowercase ) return {} def _lowerCamelCase ( lowercase : str ) -> Dict: _a = {} if os.path.exists(lowercase ): _a = os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase , lowercase ) , encoding="utf-8" ) as f: _a = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase , lowercase )}.' ) from e return _artifact def _lowerCamelCase ( ) -> str: class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str ): _a = name _a = [] def __str__( self : List[str] ): return self.name def UpperCamelCase__ ( self : str , __a : str ): self.paths.append({"name": self.name, "path": path} ) _a = {} _a = filter(os.path.isdir , os.listdir() ) for directory in directories: _a = directory if artifact_name not in _available_artifacts: _a = Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase_ : List[Any] = get_job_links() lowerCAmelCase_ : Any = retrieve_available_artifacts() lowerCAmelCase_ : List[str] = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase_ : Optional[Any] = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase_ : int = github_actions_job_links.get('run_doctests') lowerCAmelCase_ : Union[str, Any] = available_artifacts['doc_tests_gpu_test_reports'].paths[0] lowerCAmelCase_ : List[str] = retrieve_artifact(artifact_path['name']) if "stats" in artifact: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = handle_test_results(artifact['stats']) lowerCAmelCase_ : List[str] = failed lowerCAmelCase_ : Optional[Any] = success lowerCAmelCase_ : Tuple = time_spent[1:-1] + ', ' lowerCAmelCase_ : List[Any] = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): lowerCAmelCase_ : int = line.replace('FAILED ', '') lowerCAmelCase_ : Optional[int] = line.split()[0].replace('\n', '') if "::" in line: lowerCAmelCase_ , lowerCAmelCase_ : str = line.split('::') else: lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase_ : Union[str, Any] = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase_ : List[str] = all_failures[test] if test in all_failures else 'N/A' lowerCAmelCase_ : Optional[Any] = failure break lowerCAmelCase_ : Tuple = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
346
0
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCAmelCase_ : List[str] = 2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCAmelCase_ : Union[str, Any] = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCAmelCase_ : List[Any] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def _lowerCamelCase ( lowercase : str , lowercase : str ) -> tuple[str, float]: _a = len([g for position, g in enumerate(lowercase ) if g == main_target[position]] ) return (item, float(lowercase )) def _lowerCamelCase ( lowercase : str , lowercase : str ) -> tuple[str, str]: _a = random.randint(0 , len(lowercase ) - 1 ) _a = parent_a[:random_slice] + parent_a[random_slice:] _a = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = list(lowercase ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: _a = random.choice(lowercase ) return "".join(lowercase ) def _lowerCamelCase ( lowercase : tuple[str, float] , lowercase : list[tuple[str, float]] , lowercase : list[str] , ) -> list[str]: _a = [] # Generate more children proportionally to the fitness score. _a = int(parent_a[1] * 100 ) + 1 _a = 10 if child_n >= 10 else child_n for _ in range(lowercase ): _a = population_score[random.randint(0 , lowercase )][0] _a , _a = crossover(parent_a[0] , lowercase ) # Append new string to the population list. pop.append(mutate(lowercase , lowercase ) ) pop.append(mutate(lowercase , lowercase ) ) return pop def _lowerCamelCase ( lowercase : str , lowercase : list[str] , lowercase : bool = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: _a = F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowercase ) # Verify that the target contains no genes besides the ones inside genes variable. _a = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _a = F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowercase ) # Generate random starting population. _a = [] for _ in range(lowercase ): population.append("".join([random.choice(lowercase ) for i in range(len(lowercase ) )] ) ) # Just some logs to know what the algorithms is doing. _a , _a = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _a = [evaluate(lowercase , lowercase ) for item in population] # Check if there is a matching evolution. _a = sorted(lowercase , key=lambda lowercase : x[1] , reverse=lowercase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _a = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase ) # Normalize population score to be between 0 and 1. _a = [ (item, score / len(lowercase )) for item, score in population_score ] # This is selection for i in range(lowercase ): population.extend(select(population_score[int(lowercase )] , lowercase , lowercase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase ) > N_POPULATION: break if __name__ == "__main__": lowerCAmelCase_ : List[Any] = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) lowerCAmelCase_ : Any = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) lowerCAmelCase_ : Any = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
355
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCamelCase ( ) -> str: _a = HfArgumentParser(lowercase ) _a = parser.parse_args_into_dataclasses()[0] _a = TensorFlowBenchmark(args=lowercase ) try: _a = parser.parse_args_into_dataclasses()[0] except ValueError as e: _a = "Arg --no_{0} is no longer used, please use --no-{0} instead." _a = " ".join(str(lowercase ).split(" " )[:-1] ) _a = "" _a = eval(str(lowercase ).split(" " )[-1] ) _a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowercase ) if len(lowercase ) > 0: _a = full_error_msg + begin_error_msg + str(lowercase ) raise ValueError(lowercase ) benchmark.run() if __name__ == "__main__": main()
346
0
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def _lowerCamelCase ( lowercase : np.ndarray , lowercase : np.ndarray , lowercase : np.ndarray , lowercase : int , lowercase : int ) -> np.ndarray: _a = cva.getAffineTransform(lowercase , lowercase ) return cva.warpAffine(lowercase , lowercase , (rows, cols) ) if __name__ == "__main__": # read original image lowerCAmelCase_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value lowerCAmelCase_ : Optional[int] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape lowerCAmelCase_ : int = gray_img.shape # set different points to rotate image lowerCAmelCase_ : str = np.array([[50, 50], [2_00, 50], [50, 2_00]], np.floataa) lowerCAmelCase_ : Union[str, Any] = np.array([[10, 1_00], [2_00, 50], [1_00, 2_50]], np.floataa) lowerCAmelCase_ : List[Any] = np.array([[50, 50], [1_50, 50], [1_20, 2_00]], np.floataa) lowerCAmelCase_ : Union[str, Any] = np.array([[10, 1_00], [80, 50], [1_80, 2_50]], np.floataa) # add all rotated images in a list lowerCAmelCase_ : Dict = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations lowerCAmelCase_ : Optional[int] = plt.figure(1) lowerCAmelCase_ : List[Any] = ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3'] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray') plt.title(titles[i]) plt.axis('off') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
356
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ : Union[str, Any] = None try: import msvcrt except ImportError: lowerCAmelCase_ : Tuple = None try: import fcntl except ImportError: lowerCAmelCase_ : Optional[int] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ : Any = OSError # Data # ------------------------------------------------ lowerCAmelCase_ : Tuple = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] lowerCAmelCase_ : Optional[int] = '3.0.12' lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( ) -> Optional[int]: global _logger _a = _logger or logging.getLogger(__name__ ) return _logger class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict , __a : Optional[Any] ): _a = lock_file return None def __str__( self : Any ): _a = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , __a : Optional[int] ): _a = lock return None def __enter__( self : str ): return self.lock def __exit__( self : List[Any] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): self.lock.release() return None class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] , __a : Optional[int]=-1 , __a : Tuple=None ): _a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long _a = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. _a = 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. _a = None # The default timeout value. _a = timeout # We use this lock primarily for the lock counter. _a = 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. _a = 0 return None @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file @property def UpperCamelCase__ ( self : List[Any] ): return self._timeout @timeout.setter def UpperCamelCase__ ( self : int , __a : List[Any] ): _a = float(__a ) return None def UpperCamelCase__ ( self : Dict ): raise NotImplementedError() def UpperCamelCase__ ( self : str ): raise NotImplementedError() @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file_fd is not None def UpperCamelCase__ ( self : int , __a : int=None , __a : Tuple=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: _a = 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 _a = id(self ) _a = self._lock_file _a = 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(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: _a = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: _a = id(self ) _a = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() _a = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : List[Any] ): self.acquire() return self def __exit__( self : str , __a : str , __a : Dict , __a : Dict ): self.release() return None def __del__( self : int ): self.release(force=__a ) return None def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): _a = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: _a = os.path.dirname(__a ) _a = str(hash(__a ) ) _a = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , __a : str , __a : List[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) _a = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def UpperCamelCase__ ( self : int ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Optional[Any] ): _a = self._lock_file_fd _a = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=-1 , __a : int=None ): _a = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def UpperCamelCase__ ( self : Any ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC _a = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Tuple ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition _a = self._lock_file_fd _a = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): _a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: _a = fd return None def UpperCamelCase__ ( self : Union[str, Any] ): os.close(self._lock_file_fd ) _a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ : str = None if msvcrt: lowerCAmelCase_ : List[str] = WindowsFileLock elif fcntl: lowerCAmelCase_ : List[str] = UnixFileLock else: lowerCAmelCase_ : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
357
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
0
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 __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =StableDiffusionInpaintPipeline __a =TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __a =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __a =frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __a =frozenset([] ) def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = 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=__a , ) _a = PNDMScheduler(skip_prk_steps=__a ) torch.manual_seed(0 ) _a = 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=1_28 , ) torch.manual_seed(0 ) _a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="gelu" , projection_dim=5_12 , ) _a = CLIPTextModel(__a ) _a = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _a = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def UpperCamelCase__ ( self : str , __a : Any , __a : int=0 ): # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched _a = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) _a = image.cpu().permute(0 , 2 , 3 , 1 )[0] _a = Image.fromarray(np.uinta(__a ) ).convert("RGB" ).resize((64, 64) ) _a = Image.fromarray(np.uinta(image + 4 ) ).convert("RGB" ).resize((64, 64) ) if str(__a ).startswith("mps" ): _a = torch.manual_seed(__a ) else: _a = torch.Generator(device=__a ).manual_seed(__a ) _a = { "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 : Dict ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = StableDiffusionInpaintPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = sd_pipe(**__a ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = 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 : List[str] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : List[str] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint" "/yellow_cat_sitting_on_a_park_bench.npy" ) _a = "stabilityai/stable-diffusion-2-inpainting" _a = StableDiffusionInpaintPipeline.from_pretrained(__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "Face of a yellow cat, high resolution, sitting on a park bench" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 9e-3 def UpperCamelCase__ ( self : Any ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint" "/yellow_cat_sitting_on_a_park_bench_fp16.npy" ) _a = "stabilityai/stable-diffusion-2-inpainting" _a = StableDiffusionInpaintPipeline.from_pretrained( __a , torch_dtype=torch.floataa , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "Face of a yellow cat, high resolution, sitting on a park bench" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 5e-1 def UpperCamelCase__ ( self : List[str] ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) _a = "stabilityai/stable-diffusion-2-inpainting" _a = PNDMScheduler.from_pretrained(__a , subfolder="scheduler" ) _a = StableDiffusionInpaintPipeline.from_pretrained( __a , safety_checker=__a , scheduler=__a , torch_dtype=torch.floataa , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _a = "Face of a yellow cat, high resolution, sitting on a park bench" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , mask_image=__a , generator=__a , num_inference_steps=2 , output_type="np" , ) _a = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
358
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ : List[str] = TypeVar('T') lowerCAmelCase_ : Dict = TypeVar('U') class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Union[str, Any] , __a : T | None , __a : U | None ): _a = key _a = val _a = None _a = None def __repr__( self : Any ): return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Dict ): _a = DoubleLinkedListNode(__a , __a ) _a = DoubleLinkedListNode(__a , __a ) _a , _a = self.rear, self.head def __repr__( self : str ): _a = ["DoubleLinkedList"] _a = self.head while node.next is not None: rep.append(str(__a ) ) _a = node.next rep.append(str(self.rear ) ) return ",\n ".join(__a ) def UpperCamelCase__ ( self : int , __a : DoubleLinkedListNode[T, U] ): _a = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _a = node _a = previous _a = node _a = self.rear def UpperCamelCase__ ( self : Any , __a : DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None _a = node.next _a = node.prev _a = None _a = None return node class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" __a ={} def __init__( self : Union[str, Any] , __a : int ): _a = DoubleLinkedList() _a = capacity _a = 0 _a = 0 _a = 0 _a = {} def __repr__( self : Optional[int] ): return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self : str , __a : T ): return key in self.cache def UpperCamelCase__ ( self : str , __a : T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _a = self.cache[key] _a = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__a ) return node.val self.miss += 1 return None def UpperCamelCase__ ( self : Tuple , __a : T , __a : U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _a = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _a = DoubleLinkedListNode(__a , __a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _a = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _a = value self.list.add(__a ) @classmethod def UpperCamelCase__ ( cls : Tuple , __a : int = 1_28 ): def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _a = LRUCache(__a ) _a = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _a = func(*__a ) cls.decorator_function_to_instance_map[func].put(args[0] , __a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__a , "cache_info" , __a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : Union[str, Any] = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : Dict , lowercase : Any ) -> Optional[Any]: if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: _a = TOKENIZER_CLASSES else: _a = {tokenizer_name: getattr(lowercase , tokenizer_name + "Fast" )} logger.info(F'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: _a = TOKENIZER_CLASSES[tokenizer_name] _a = True if checkpoint_name is None: _a = list(tokenizer_class.max_model_input_sizes.keys() ) else: _a = [checkpoint_name] logger.info(F'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(F'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer _a = tokenizer_class.from_pretrained(lowercase , force_download=lowercase ) # Save fast tokenizer logger.info(F'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: _a , _a = checkpoint.split("/" ) _a = os.path.join(lowercase , lowercase ) elif add_prefix: _a = checkpoint _a = dump_path else: _a = None _a = dump_path logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: _a = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] _a = file_path.split(lowercase )[-1][0] if next_char == "/": _a = os.path.join(lowercase , lowercase ) _a = None logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) _a = tokenizer.save_pretrained( lowercase , legacy_format=lowercase , filename_prefix=lowercase ) logger.info(F'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith("tokenizer.json" ): os.remove(lowercase ) logger.info(F'=> removing {file_name}' ) if __name__ == "__main__": lowerCAmelCase_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( f"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowerCAmelCase_ : Any = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
359
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowerCamelCase ( lowercase : str ) -> str: re.sub("<n>" , "" , lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowercase ) )
346
0
'''simple docstring''' import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='facebook/bart-large-mnli' __a =( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) __a ='text_classifier' __a =AutoTokenizer __a =AutoModelForSequenceClassification __a =['text', ['text']] __a =['text'] def UpperCamelCase__ ( self : str ): super().setup() _a = self.model.config _a = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): _a = int(__a ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def UpperCamelCase__ ( self : str , __a : str , __a : Optional[Any] ): _a = labels return self.pre_processor( [text] * len(__a ) , [f'This example is {label}' for label in labels] , return_tensors="pt" , padding="max_length" , ) def UpperCamelCase__ ( self : Dict , __a : Any ): _a = outputs.logits _a = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
360
'''simple docstring''' import requests lowerCAmelCase_ : List[Any] = 'YOUR API KEY' def _lowerCamelCase ( lowercase : str , lowercase : str = giphy_api_key ) -> list: _a = "+".join(query.split() ) _a = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' _a = requests.get(lowercase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
346
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Optional[Any] = { 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertConfig', 'SqueezeBertOnnxConfig', ], 'tokenization_squeezebert': ['SqueezeBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[Any] = ['SqueezeBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'SqueezeBertForMaskedLM', 'SqueezeBertForMultipleChoice', 'SqueezeBertForQuestionAnswering', 'SqueezeBertForSequenceClassification', 'SqueezeBertForTokenClassification', 'SqueezeBertModel', 'SqueezeBertModule', 'SqueezeBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys lowerCAmelCase_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =BertGenerationTokenizer __a =False __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = BertGenerationTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ ( self : Tuple ): _a = "<s>" _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[str] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__a ) , 10_02 ) def UpperCamelCase__ ( self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def UpperCamelCase__ ( self : Tuple ): _a = BertGenerationTokenizer(__a , keep_accents=__a ) _a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [2_85, 46, 10, 1_70, 3_82] , ) _a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _a = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def UpperCamelCase__ ( self : Any ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def UpperCamelCase__ ( self : List[str] ): _a = "Hello World!" _a = [1_85_36, 22_60, 1_01] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def UpperCamelCase__ ( self : Optional[int] ): _a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def UpperCamelCase__ ( self : Tuple ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _a = list(self.big_tokenizer.get_vocab().keys() )[:10] _a = " ".join(__a ) _a = self.big_tokenizer.encode_plus(__a , return_tensors="pt" , return_token_type_ids=__a ) _a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__a ) _a = BertGenerationConfig() _a = BertGenerationEncoder(__a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def UpperCamelCase__ ( self : Optional[int] ): # fmt: off _a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
346
0
'''simple docstring''' import random class __SCREAMING_SNAKE_CASE : """simple docstring""" @staticmethod def UpperCamelCase__ ( __a : str ): _a = [ord(__a ) for i in text] _a = [] _a = [] for i in plain: _a = random.randint(1 , 3_00 ) _a = (i + k) * k cipher.append(__a ) key.append(__a ) return cipher, key @staticmethod def UpperCamelCase__ ( __a : list[int] , __a : list[int] ): _a = [] for i in range(len(__a ) ): _a = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(__a ) ) return "".join(__a ) if __name__ == "__main__": lowerCAmelCase_ : Dict = Onepad().encrypt('Hello') print(c, k) print(Onepad().decrypt(c, k))
362
'''simple docstring''' def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Union[str, Any]: _enforce_args(lowercase , lowercase ) if n == 0: return 0 _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase ) ) return max_revue def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Tuple: _enforce_args(lowercase , lowercase ) _a = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase , lowercase , lowercase ) def _lowerCamelCase ( lowercase : int , lowercase : list , lowercase : list ) -> List[str]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase , lowercase ) , ) _a = max_revenue return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Any: _enforce_args(lowercase , lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _a = [float("-inf" ) for _ in range(n + 1 )] _a = 0 for i in range(1 , n + 1 ): _a = max_rev[i] for j in range(1 , i + 1 ): _a = max(lowercase , prices[j - 1] + max_rev[i - j] ) _a = max_revenue_i return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Dict: if n < 0: _a = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): _a = ( "Each integral piece of rod must have a corresponding price. " F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def _lowerCamelCase ( ) -> Any: _a = [6, 10, 12, 15, 20, 23] _a = len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _a = 36 _a = top_down_cut_rod(lowercase , lowercase ) _a = bottom_up_cut_rod(lowercase , lowercase ) _a = naive_cut_rod_recursive(lowercase , lowercase ) 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()
346
0
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ : Any = 16 lowerCAmelCase_ : List[Any] = 32 def _lowerCamelCase ( lowercase : Accelerator , lowercase : int = 16 ) -> Optional[Any]: _a = AutoTokenizer.from_pretrained("bert-base-cased" ) _a = load_dataset("glue" , "mrpc" ) def tokenize_function(lowercase : List[str] ): # max_length=None => use the model max length (it's actually the default) _a = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowercase , max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a = datasets.map( lowercase , batched=lowercase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowercase : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. _a = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a = 16 elif accelerator.mixed_precision != "no": _a = 8 else: _a = None return tokenizer.pad( lowercase , padding="longest" , max_length=lowercase , pad_to_multiple_of=lowercase , return_tensors="pt" , ) # Instantiate dataloaders. _a = DataLoader( tokenized_datasets["train"] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) _a = DataLoader( tokenized_datasets["validation"] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase_ : List[str] = mocked_dataloaders # noqa: F811 def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Optional[Any]: # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowercase ) == "1": _a = 2 # Initialize accelerator _a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a = config["lr"] _a = int(config["num_epochs"] ) _a = int(config["seed"] ) _a = int(config["batch_size"] ) _a = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation _a = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a = batch_size // MAX_GPU_BATCH_SIZE _a = MAX_GPU_BATCH_SIZE set_seed(lowercase ) _a , _a = get_dataloaders(lowercase , lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowercase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a = model.to(accelerator.device ) # Instantiate optimizer _a = AdamW(params=model.parameters() , lr=lowercase ) # Instantiate scheduler _a = get_linear_schedule_with_warmup( optimizer=lowercase , num_warmup_steps=100 , num_training_steps=(len(lowercase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a , _a , _a , _a , _a = accelerator.prepare( lowercase , lowercase , lowercase , lowercase , lowercase ) # Now we train the model for epoch in range(lowercase ): model.train() for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a = model(**lowercase ) _a = outputs.loss _a = loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a = 0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a = model(**lowercase ) _a = outputs.logits.argmax(dim=-1 ) _a , _a = accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(lowercase ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=lowercase , references=lowercase , ) _a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , lowercase ) def _lowerCamelCase ( ) -> List[str]: _a = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowercase , default=lowercase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) _a = parser.parse_args() _a = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowercase , lowercase ) if __name__ == "__main__": main()
363
'''simple docstring''' 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_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , *__a : Optional[int] , **__a : List[str] ): super().__init__(*__a , **__a ) self.check_model_type(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : int=None , __a : Optional[Any]=None , **__a : List[Any] ): _a , _a = {}, {} if padding is not None: _a = padding if truncation is not None: _a = truncation if top_k is not None: _a = top_k return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __a : Union["Image.Image", str] , __a : str = None , **__a : Any ): if isinstance(__a , (Image.Image, str) ) and isinstance(__a , __a ): _a = {"image": image, "question": question} else: _a = image _a = super().__call__(__a , **__a ) return results def UpperCamelCase__ ( self : Tuple , __a : Tuple , __a : Optional[Any]=False , __a : List[Any]=False ): _a = load_image(inputs["image"] ) _a = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=__a , truncation=__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) model_inputs.update(__a ) return model_inputs def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.sigmoid()[0] _a , _a = probs.topk(__a ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
346
0
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : List[Any] = logging.get_logger(__name__) lowerCAmelCase_ : Union[str, Any] = { 'microsoft/xprophetnet-large-wiki100-cased': ( 'https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='xlm-prophetnet' __a =['past_key_values'] __a ={ 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self : Dict , __a : Optional[float] = 0.1 , __a : Optional[Union[str, Callable]] = "gelu" , __a : Optional[int] = 3_05_22 , __a : Optional[int] = 10_24 , __a : Optional[int] = 40_96 , __a : Optional[int] = 12 , __a : Optional[int] = 16 , __a : Optional[int] = 40_96 , __a : Optional[int] = 12 , __a : Optional[int] = 16 , __a : Optional[float] = 0.1 , __a : Optional[float] = 0.1 , __a : Optional[int] = 5_12 , __a : Optional[float] = 0.02 , __a : Optional[bool] = True , __a : Optional[bool] = True , __a : Optional[int] = 0 , __a : Optional[int] = 2 , __a : Optional[int] = 32 , __a : Optional[int] = 1_28 , __a : Optional[bool] = False , __a : Optional[float] = 0.0 , __a : Optional[bool] = True , __a : Optional[int] = 0 , __a : Optional[int] = 1 , __a : Optional[int] = 2 , **__a : Optional[Any] , ): _a = vocab_size _a = hidden_size _a = encoder_ffn_dim _a = num_encoder_layers _a = num_encoder_attention_heads _a = decoder_ffn_dim _a = num_decoder_layers _a = num_decoder_attention_heads _a = max_position_embeddings _a = init_std # Normal(0, this parameter) _a = activation_function # parameters for xlmprophetnet _a = ngram _a = num_buckets _a = relative_max_distance _a = disable_ngram_loss _a = eps # 3 Types of Dropout _a = attention_dropout _a = activation_dropout _a = dropout _a = use_cache super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , add_cross_attention=__a , decoder_start_token_id=__a , **__a , ) @property def UpperCamelCase__ ( self : Any ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase__ ( self : int , __a : Tuple ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
364
'''simple docstring''' from random import randint, random def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : bool = False , lowercase : int = 5 , ) -> list: _a = [[-1] * number_of_cells] # Create a highway without any car _a = 0 _a = max(lowercase , 0 ) while i < number_of_cells: _a = ( randint(0 , lowercase ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( lowercase : list , lowercase : int ) -> int: _a = 0 _a = highway_now[car_index + 1 :] for cell in range(len(lowercase ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(lowercase , -1 ) def _lowerCamelCase ( lowercase : list , lowercase : float , lowercase : int ) -> list: _a = len(lowercase ) # Beforce calculations, the highway is empty _a = [-1] * number_of_cells for car_index in range(lowercase ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _a = min(highway_now[car_index] + 1 , lowercase ) # Number of empty cell before the next car _a = get_distance(lowercase , lowercase ) - 1 # We can't have the car causing an accident _a = min(next_highway[car_index] , lowercase ) if random() < probability: # Randomly, a driver will slow down _a = max(next_highway[car_index] - 1 , 0 ) return next_highway def _lowerCamelCase ( lowercase : list , lowercase : int , lowercase : float , lowercase : int ) -> list: _a = len(highway[0] ) for i in range(lowercase ): _a = update(highway[i] , lowercase , lowercase ) _a = [-1] * number_of_cells for car_index in range(lowercase ): _a = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _a = (car_index + speed) % number_of_cells # Commit the change of position _a = speed highway.append(lowercase ) return highway if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : str = logging.get_logger(__name__) lowerCAmelCase_ : Any = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='encodec' def __init__( self : int , __a : str=[1.5, 3.0, 6.0, 12.0, 24.0] , __a : Optional[int]=2_40_00 , __a : str=1 , __a : List[str]=False , __a : Union[str, Any]=None , __a : List[str]=None , __a : str=1_28 , __a : Any=32 , __a : Dict=1 , __a : Tuple=[8, 5, 4, 2] , __a : List[str]="weight_norm" , __a : List[Any]=7 , __a : Any=7 , __a : List[Any]=3 , __a : Optional[int]=2 , __a : List[Any]=True , __a : Optional[Any]="reflect" , __a : Union[str, Any]=2 , __a : Optional[int]=2 , __a : Union[str, Any]=1.0 , __a : Any=10_24 , __a : Tuple=None , __a : Optional[Any]=True , **__a : Dict , ): _a = target_bandwidths _a = sampling_rate _a = audio_channels _a = normalize _a = chunk_length_s _a = overlap _a = hidden_size _a = num_filters _a = num_residual_layers _a = upsampling_ratios _a = norm_type _a = kernel_size _a = last_kernel_size _a = residual_kernel_size _a = dilation_growth_rate _a = use_causal_conv _a = pad_mode _a = compress _a = num_lstm_layers _a = trim_right_ratio _a = codebook_size _a = codebook_dim if codebook_dim is not None else hidden_size _a = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}' ) super().__init__(**__a ) @property def UpperCamelCase__ ( self : Dict ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def UpperCamelCase__ ( self : Dict ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def UpperCamelCase__ ( self : Any ): _a = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def UpperCamelCase__ ( self : Optional[Any] ): return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
365
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
346
0
'''simple docstring''' from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['audio_values', 'audio_mask'] def __init__( self : List[str] , __a : Optional[Any]=20_48 , __a : Optional[Any]=1 , __a : Tuple=[16, 16] , __a : List[str]=1_28 , __a : str=4_41_00 , __a : int=86 , __a : Any=20_48 , __a : Dict=0.0 , **__a : Tuple , ): super().__init__( feature_size=__a , sampling_rate=__a , padding_value=__a , **__a , ) _a = spectrogram_length _a = num_channels _a = patch_size _a = feature_size // self.patch_size[1] _a = n_fft _a = sampling_rate // hop_length_to_sampling_rate _a = sampling_rate _a = padding_value _a = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__a , min_frequency=0.0 , max_frequency=22050.0 , sampling_rate=__a , norm="slaney" , mel_scale="slaney" , ).T def UpperCamelCase__ ( self : Dict , __a : np.array ): _a = spectrogram( __a , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel="dB" , db_range=80.0 , ) _a = log_spec[:, :-1] _a = log_spec - 20.0 _a = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self : str , __a : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __a : Optional[Union[str, TensorType]] = None , __a : Optional[bool] = True , __a : Optional[int] = None , __a : bool = False , __a : bool = False , **__a : str , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( "This feature extractor is set to support sampling rate" f' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled' f' with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) _a = isinstance(__a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) _a = is_batched_numpy or ( isinstance(__a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _a = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__a , np.ndarray ): _a = np.asarray(__a , dtype=np.floataa ) elif isinstance(__a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _a = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis _a = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , __a ): _a = [np.asarray(__a , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask _a = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: _a = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] _a = np.array(__a ).astype(np.floataa ) # convert into correct format for padding _a = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch _a = np.ones([len(__a ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) _a = padded_audio_features * self.padding_value for i in range(len(__a ) ): _a = audio_features[i] _a = feature # return as BatchFeature if return_attention_mask: _a = {"audio_values": padded_audio_features, "audio_mask": audio_mask} else: _a = {"audio_values": padded_audio_features} _a = BatchFeature(data=__a , tensor_type=__a ) return encoded_inputs
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 lowerCAmelCase_ : Optional[Any] = get_tests_dir('fixtures') lowerCAmelCase_ : Optional[Any] = get_tests_dir('fixtures/dummy_feature_extractor_config.json') lowerCAmelCase_ : Optional[Any] = get_tests_dir('fixtures/dummy-config.json') class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : int ): _a = 0 def UpperCamelCase__ ( self : Dict ): _a = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" ) self.assertIsInstance(__a , __a ) def UpperCamelCase__ ( self : Optional[Any] ): _a = AutoFeatureExtractor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def UpperCamelCase__ ( self : Any ): with tempfile.TemporaryDirectory() as tmpdirname: _a = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally _a = AutoFeatureExtractor.from_pretrained(__a ).to_dict() config_dict.pop("feature_extractor_type" ) _a = WavaVecaFeatureExtractor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) _a = AutoFeatureExtractor.from_pretrained(__a ) # make sure private variable is not incorrectly saved _a = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def UpperCamelCase__ ( self : Optional[Any] ): _a = AutoFeatureExtractor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def UpperCamelCase__ ( self : int ): with self.assertRaisesRegex( __a , "bert-base is not a local folder and is not a valid model identifier" ): _a = AutoFeatureExtractor.from_pretrained("bert-base" ) def UpperCamelCase__ ( self : Tuple ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): _a = AutoFeatureExtractor.from_pretrained(__a , revision="aaaaaa" ) def UpperCamelCase__ ( self : str ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): _a = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" ) def UpperCamelCase__ ( self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=__a ) _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=__a ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__a ) _a = AutoFeatureExtractor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) def UpperCamelCase__ ( self : List[str] ): try: AutoConfig.register("custom" , __a ) AutoFeatureExtractor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoFeatureExtractor.register(__a , __a ) # Now that the config is registered, it can be used as any other config with the auto-API _a = CustomFeatureExtractor.from_pretrained(__a ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__a ) _a = AutoFeatureExtractor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def UpperCamelCase__ ( self : List[Any] ): class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =True try: AutoConfig.register("custom" , __a ) AutoFeatureExtractor.register(__a , __a ) # If remote code is not set, the default is to use local _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=__a ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub _a = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=__a ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
367
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ : List[Any] = logging.getLogger(__name__) lowerCAmelCase_ : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowerCAmelCase_ : int = {'facebook/bart-base': BartTokenizer} def _lowerCamelCase ( ) -> Union[str, Any]: _a = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=lowercase , default=lowercase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=lowercase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowercase , default=lowercase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowercase , ) parser.add_argument( "--config_name" , type=lowercase , default=lowercase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowercase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowercase , default=lowercase , help="Where to store the final ONNX file." ) _a = parser.parse_args() return args def _lowerCamelCase ( lowercase : Any , lowercase : Tuple="cpu" ) -> Optional[Any]: _a = model_dict[model_name].from_pretrained(lowercase ).to(lowercase ) _a = tokenizer_dict[model_name].from_pretrained(lowercase ) if model_name in ["facebook/bart-base"]: _a = 0 _a = None _a = 0 return huggingface_model, tokenizer def _lowerCamelCase ( lowercase : List[str] , lowercase : Tuple , lowercase : int , lowercase : Any , lowercase : Dict ) -> Any: model.eval() _a = None _a = torch.jit.script(BARTBeamSearchGenerator(lowercase ) ) with torch.no_grad(): _a = "My friends are cool but they eat too many carbs." _a = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) _a = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowercase , max_length=lowercase , early_stopping=lowercase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowercase , ) logger.info("Model exported to {}".format(lowercase ) ) _a = remove_dup_initializers(os.path.abspath(lowercase ) ) logger.info("Deduplicated and optimized model written to {}".format(lowercase ) ) _a = onnxruntime.InferenceSession(lowercase ) _a = ort_sess.run( lowercase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowercase ), "max_length": np.array(lowercase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def _lowerCamelCase ( ) -> Any: _a = parse_args() _a = 5 _a = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _a = torch.device(args.device ) _a , _a = load_model_tokenizer(args.model_name_or_path , lowercase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(lowercase ) if args.max_length: _a = args.max_length if args.num_beams: _a = args.num_beams if args.output_file_path: _a = args.output_file_path else: _a = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(lowercase , lowercase , lowercase , lowercase , lowercase ) if __name__ == "__main__": main()
346
0
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Optional[Any]=False ) -> Dict: try: _a = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _a = default else: # KEY is set, convert it to True or False. try: _a = strtobool(lowercase ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'If set, {key} must be yes or no.' ) return _value lowerCAmelCase_ : Dict = parse_flag_from_env('RUN_SLOW', default=False) lowerCAmelCase_ : Optional[Any] = parse_flag_from_env('RUN_REMOTE', default=False) lowerCAmelCase_ : int = parse_flag_from_env('RUN_LOCAL', default=True) lowerCAmelCase_ : Any = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression lowerCAmelCase_ : List[str] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') lowerCAmelCase_ : Optional[Any] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') lowerCAmelCase_ : Union[str, Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio lowerCAmelCase_ : Union[str, Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam lowerCAmelCase_ : List[Any] = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility lowerCAmelCase_ : Dict = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows lowerCAmelCase_ : Any = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowerCamelCase ( lowercase : List[str] ) -> int: try: import faiss # noqa except ImportError: _a = unittest.skip("test requires faiss" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Dict ) -> Any: try: import regex # noqa except ImportError: _a = unittest.skip("test requires regex" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[Any]: try: import elasticsearch # noqa except ImportError: _a = unittest.skip("test requires elasticsearch" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Optional[Any] ) -> str: try: import sqlalchemy # noqa except ImportError: _a = unittest.skip("test requires sqlalchemy" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: if not config.TORCH_AVAILABLE: _a = unittest.skip("test requires PyTorch" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Dict ) -> Tuple: if not config.TF_AVAILABLE: _a = unittest.skip("test requires TensorFlow" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Optional[int] ) -> Any: if not config.JAX_AVAILABLE: _a = unittest.skip("test requires JAX" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Any ) -> int: if not config.PIL_AVAILABLE: _a = unittest.skip("test requires Pillow" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : int ) -> Tuple: try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers" )(lowercase ) else: return test_case def _lowerCamelCase ( lowercase : int ) -> str: try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken" )(lowercase ) else: return test_case def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Any: try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy" )(lowercase ) else: return test_case def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[Any]: def _require_spacy_model(lowercase : int ): try: import spacy # noqa F401 spacy.load(lowercase ) except ImportError: return unittest.skip("test requires spacy" )(lowercase ) except OSError: return unittest.skip("test requires spacy model '{}'".format(lowercase ) )(lowercase ) else: return test_case return _require_spacy_model def _lowerCamelCase ( lowercase : Dict ) -> Tuple: try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark" )(lowercase ) else: return test_case def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Tuple: try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark" )(lowercase ) else: return test_case def _lowerCamelCase ( lowercase : Tuple ) -> Tuple: if not _run_slow_tests or _run_slow_tests == 0: _a = unittest.skip("test is slow" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : List[str] ) -> List[str]: if not _run_local_tests or _run_local_tests == 0: _a = unittest.skip("test is local" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : Tuple ) -> Dict: if not _run_packaged_tests or _run_packaged_tests == 0: _a = unittest.skip("test is packaged" )(lowercase ) return test_case def _lowerCamelCase ( lowercase : str ) -> Dict: if not _run_remote_tests or _run_remote_tests == 0: _a = unittest.skip("test requires remote" )(lowercase ) return test_case def _lowerCamelCase ( *lowercase : str ) -> int: def decorate(cls : str ): for name, fn in cls.__dict__.items(): if callable(lowercase ) and name.startswith("test" ): for decorator in decorators: _a = decorator(lowercase ) setattr(cls , lowercase , lowercase ) return cls return decorate class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" pass class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =0 __a =1 __a =2 @contextmanager def _lowerCamelCase ( lowercase : Optional[int]=OfflineSimulationMode.CONNECTION_FAILS , lowercase : Dict=1E-1_6 ) -> str: _a = requests.Session().request def timeout_request(lowercase : Tuple , lowercase : List[Any] , lowercase : List[Any] , **lowercase : Optional[int] ): # Change the url to an invalid url so that the connection hangs _a = "https://10.255.255.1" if kwargs.get("timeout" ) is None: raise RequestWouldHangIndefinitelyError( F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.' ) _a = timeout try: return online_request(lowercase , lowercase , **lowercase ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier _a = url _a = e.args[0] _a = (max_retry_error.args[0].replace("10.255.255.1" , F'OfflineMock[{url}]' ),) _a = (max_retry_error,) raise def raise_connection_error(lowercase : Any , lowercase : Any , **lowercase : Union[str, Any] ): raise requests.ConnectionError("Offline mode is enabled." , request=lowercase ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" , lowercase ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" , lowercase ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" , lowercase ): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum." ) @contextmanager def _lowerCamelCase ( *lowercase : Tuple , **lowercase : List[str] ) -> Dict: _a = str(Path().resolve() ) with tempfile.TemporaryDirectory(*lowercase , **lowercase ) as tmp_dir: try: os.chdir(lowercase ) yield finally: os.chdir(lowercase ) @contextmanager def _lowerCamelCase ( ) -> int: import gc gc.collect() _a = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowerCamelCase ( ) -> Optional[int]: import gc gc.collect() _a = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowerCamelCase ( lowercase : Tuple , lowercase : Optional[Any] ) -> Optional[int]: return deepcopy(lowercase ).integers(0 , 100 , 10 ).tolist() == deepcopy(lowercase ).integers(0 , 100 , 10 ).tolist() def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: import decorator from requests.exceptions import HTTPError def _wrapper(lowercase : Tuple , *lowercase : List[Any] , **lowercase : Union[str, Any] ): try: return func(*lowercase , **lowercase ) except HTTPError as err: if str(lowercase ).startswith("500" ) or str(lowercase ).startswith("502" ): pytest.xfail(str(lowercase ) ) raise err return decorator.decorator(_wrapper , lowercase ) class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Optional[int] , __a : List[str] , __a : int , __a : List[str] ): _a = returncode _a = stdout _a = stderr async def _lowerCamelCase ( lowercase : List[Any] , lowercase : Tuple ) -> Optional[Any]: while True: _a = await stream.readline() if line: callback(lowercase ) else: break async def _lowerCamelCase ( lowercase : Any , lowercase : Dict=None , lowercase : Dict=None , lowercase : Optional[Any]=None , lowercase : Optional[int]=False , lowercase : Tuple=False ) -> _RunOutput: if echo: print("\nRunning: " , " ".join(lowercase ) ) _a = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowercase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowercase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) _a = [] _a = [] def tee(lowercase : Union[str, Any] , lowercase : Tuple , lowercase : str , lowercase : Dict="" ): _a = line.decode("utf-8" ).rstrip() sink.append(lowercase ) if not quiet: print(lowercase , lowercase , file=lowercase ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda lowercase : tee(lowercase , lowercase , sys.stdout , label="stdout:" ) ), _read_stream(p.stderr , lambda lowercase : tee(lowercase , lowercase , sys.stderr , label="stderr:" ) ), ] , timeout=lowercase , ) return _RunOutput(await p.wait() , lowercase , lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : Optional[Any]=None , lowercase : str=None , lowercase : List[str]=180 , lowercase : Dict=False , lowercase : Optional[int]=True ) -> _RunOutput: _a = asyncio.get_event_loop() _a = loop.run_until_complete( _stream_subprocess(lowercase , env=lowercase , stdin=lowercase , timeout=lowercase , quiet=lowercase , echo=lowercase ) ) _a = " ".join(lowercase ) if result.returncode > 0: _a = "\n".join(result.stderr ) raise RuntimeError( F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n' F'The combined stderr from workers follows:\n{stderr}' ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F'\'{cmd_str}\' produced no output.' ) return result def _lowerCamelCase ( ) -> Dict: _a = os.environ.get("PYTEST_XDIST_WORKER" , "gw0" ) _a = re.sub(r"^gw" , "" , lowercase , 0 , re.M ) return int(lowercase ) def _lowerCamelCase ( ) -> List[Any]: _a = 2_9500 _a = pytest_xdist_worker_id() return port + uniq_delta
368
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCAmelCase_ : Dict = abspath(join(dirname(dirname(dirname(__file__))), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _lowerCamelCase ( lowercase : str ) -> Optional[int]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase ) def _lowerCamelCase ( lowercase : Dict ) -> str: from transformers.testing_utils import pytest_terminal_summary_main _a = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(lowercase , id=lowercase )
346
0
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowerCAmelCase_ : Tuple = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , *__a : Dict , **__a : Any ): super().__init__(*__a , **__a ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def UpperCamelCase__ ( self : Dict , __a : Dict=None ): _a = {} if top_k is not None: _a = top_k return {}, {}, postprocess_params def __call__( self : Any , __a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **__a : Tuple ): return super().__call__(__a , **__a ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] ): _a = load_image(__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) return model_inputs def UpperCamelCase__ ( self : str , __a : str ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : Dict , __a : Union[str, Any] , __a : Any=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.softmax(-1 )[0] _a , _a = probs.topk(__a ) elif self.framework == "tf": _a = stable_softmax(model_outputs.logits , axis=-1 )[0] _a = tf.math.top_k(__a , k=__a ) _a , _a = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
369
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @register_to_config def __init__( self : List[Any] , __a : int , __a : int , __a : int , __a : float , __a : int , __a : int , __a : int , __a : int , __a : str , __a : bool = False , ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.Embedding(__a , __a ) _a = False _a = nn.Dropout(p=__a ) _a = TaConfig( vocab_size=__a , d_model=__a , num_heads=__a , d_kv=__a , d_ff=__a , dropout_rate=__a , feed_forward_proj=__a , is_decoder=__a , is_encoder_decoder=__a , ) _a = nn.ModuleList() for lyr_num in range(__a ): _a = TaBlock(__a ) self.encoders.append(__a ) _a = TaLayerNorm(__a ) _a = nn.Dropout(p=__a ) def UpperCamelCase__ ( self : str , __a : Union[str, Any] , __a : Dict ): _a = self.token_embedder(__a ) _a = encoder_input_tokens.shape[1] _a = torch.arange(__a , device=encoder_input_tokens.device ) x += self.position_encoding(__a ) _a = self.dropout_pre(__a ) # inverted the attention mask _a = encoder_input_tokens.size() _a = self.get_extended_attention_mask(__a , __a ) for lyr in self.encoders: _a = lyr(__a , __a )[0] _a = self.layer_norm(__a ) return self.dropout_post(__a ), encoder_inputs_mask
346
0
'''simple docstring''' import argparse import os import re import packaging.version lowerCAmelCase_ : Dict = 'examples/' lowerCAmelCase_ : str = { 'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), 'setup': (re.compile(R'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), R'\1version="VERSION",'), 'doc': (re.compile(R'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'), } lowerCAmelCase_ : Dict = { 'init': 'src/diffusers/__init__.py', 'setup': 'setup.py', } lowerCAmelCase_ : Tuple = 'README.md' def _lowerCamelCase ( lowercase : List[str] , lowercase : List[str] , lowercase : Any ) -> List[str]: with open(lowercase , "r" , encoding="utf-8" , newline="\n" ) as f: _a = f.read() _a , _a = REPLACE_PATTERNS[pattern] _a = replace.replace("VERSION" , lowercase ) _a = re_pattern.sub(lowercase , lowercase ) with open(lowercase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(lowercase ) def _lowerCamelCase ( lowercase : List[str] ) -> Optional[Any]: for folder, directories, fnames in os.walk(lowercase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(lowercase , lowercase ) , lowercase , pattern="examples" ) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict=False ) -> Dict: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowercase , lowercase , lowercase ) if not patch: update_version_in_examples(lowercase ) def _lowerCamelCase ( ) -> Any: _a = "🤗 Transformers currently provides the following architectures" _a = "1. Want to contribute a new model?" with open(lowercase , "r" , encoding="utf-8" , newline="\n" ) as f: _a = f.readlines() # Find the start of the list. _a = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _a = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): _a = lines[index].replace( "https://huggingface.co/docs/diffusers/main/model_doc" , "https://huggingface.co/docs/diffusers/model_doc" , ) index += 1 with open(lowercase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(lowercase ) def _lowerCamelCase ( ) -> List[Any]: with open(REPLACE_FILES["init"] , "r" ) as f: _a = f.read() _a = REPLACE_PATTERNS["init"][0].search(lowercase ).groups()[0] return packaging.version.parse(lowercase ) def _lowerCamelCase ( lowercase : Dict=False ) -> Union[str, Any]: _a = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: _a = default_version.base_version elif patch: _a = F'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: _a = F'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. _a = input(F'Which version are you releasing? [{default_version}]' ) if len(lowercase ) == 0: _a = default_version print(F'Updating version to {version}.' ) global_version_update(lowercase , patch=lowercase ) def _lowerCamelCase ( ) -> Dict: _a = get_version() _a = F'{current_version.major}.{current_version.minor + 1}.0.dev0' _a = current_version.base_version # Check with the user we got that right. _a = input(F'Which version are we developing now? [{dev_version}]' ) if len(lowercase ) == 0: _a = dev_version print(F'Updating version to {version}.' ) global_version_update(lowercase ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": lowerCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.') parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.') lowerCAmelCase_ : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('Nothing to do after a patch :-)') else: post_release_work()
370
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Any: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : List[str] = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Union[str, Any]: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": _a = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Dict , lowercase : Dict ) -> str: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Tuple , __a : Optional[int] , __a : Any ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Tuple , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Dict=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : List[Any] , __a : Dict ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Union[str, Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Optional[int] , __a : pl.Trainer , __a : str ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
346
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int ) -> int: _a = [1] _a , _a , _a = 0, 0, 0 _a = ugly_nums[ia] * 2 _a = ugly_nums[ia] * 3 _a = ugly_nums[ia] * 5 for _ in range(1 , lowercase ): _a = min(lowercase , lowercase , lowercase ) ugly_nums.append(lowercase ) if next_num == next_a: ia += 1 _a = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 _a = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 _a = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"""{ugly_numbers(2_00) = }""")
371
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): lowerCAmelCase_ : str = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ : Union[str, Any] = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = (images / 2 + 0.5).clamp(0 , 1 ) _a = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _a = numpy_to_pil(lowercase ) return images def _lowerCamelCase ( lowercase : int ) -> List[Any]: if images.ndim == 3: _a = images[None, ...] _a = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _a = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: _a = [Image.fromarray(lowercase ) for image in images] return pil_images
346
0
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def _lowerCamelCase ( lowercase : Tuple=32 , lowercase : Tuple=10 , lowercase : Dict=100 , lowercase : Tuple=1026 , lowercase : Union[str, Any]=True , lowercase : Optional[int]="data/tokenized_stories_train_wikitext103.jbl" , lowercase : Tuple="igf_context_pairs.jbl" , ) -> int: set_seed(3 ) # generate train_data and objective_set _a , _a = generate_datasets( lowercase , lowercase , number=lowercase , min_len=1026 , trim=lowercase ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _a = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # load pretrained model _a = load_gpta("gpt2" ).to(lowercase ) print("computing perplexity on objective set" ) _a = compute_perplexity(lowercase , lowercase , lowercase ).item() print("perplexity on objective set:" , lowercase ) # collect igf pairs and save to file demo.jbl collect_objective_set(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Union[str, Any]=15 , lowercase : int=128 , lowercase : Union[str, Any]=100 , lowercase : Any="igf_model.pt" , ) -> Optional[Any]: set_seed(42 ) # Load pre-trained model _a = GPTaLMHeadModel.from_pretrained("gpt2" ) # Initialize secondary learner to use embedding weights of model _a = SecondaryLearner(lowercase ) # Train secondary learner _a = train_secondary_learner( lowercase , lowercase , max_epochs=lowercase , batch_size=lowercase , eval_freq=100 , igf_model_path=lowercase , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : List[str] , lowercase : List[str] , lowercase : Tuple=32 , lowercase : List[Any]=1000 , lowercase : List[Any]=16 , lowercase : Any=1.0 , lowercase : int=recopy_gpta , lowercase : Optional[Any]=None , lowercase : Optional[int]=10 , lowercase : List[str]="gpt2_finetuned.pt" , ) -> Optional[int]: _a = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) _a = RandomSampler(lowercase ) _a = DataLoader(lowercase , sampler=lowercase ) _a = max_steps // (len(lowercase )) + 1 _a = 0 _a = torch.zeros((1, context_len) , dtype=torch.long , device=lowercase ) _a , _a , _a = recopy_model(lowercase , lowercase , lowercase ) model.train() if secondary_learner is not None: secondary_learner.to(lowercase ) secondary_learner.eval() _a = [] _a = 0 _a = [] _a = [] # Compute the performance of the transformer model at the beginning _a = compute_perplexity(lowercase , lowercase , lowercase ) test_perps.append(lowercase ) print("Test perplexity, step" , lowercase , ":" , lowercase ) for epoch in range(int(lowercase ) ): for step, example in enumerate(lowercase ): torch.cuda.empty_cache() _a = random.randint(0 , example.size(2 ) - context_len - 1 ) _a = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _a = model(lowercase , labels=lowercase ) _a = True if secondary_learner is not None: _a = secondary_learner.forward( torch.tensor(lowercase , dtype=torch.long , device=lowercase ).unsqueeze(0 ) )[0].item() observed_qs.append(float(lowercase ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _a = -1 if predicted_q < threshold: _a = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _a = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _a = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _a = compute_perplexity(lowercase , lowercase , lowercase ) test_perps.append(lowercase ) print("Test perplexity, step" , lowercase , ":" , lowercase ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , lowercase ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def _lowerCamelCase ( ) -> Optional[int]: _a = argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task" ) # Required parameters parser.add_argument( "--data_dir" , default=lowercase , type=lowercase , required=lowercase , help="The input data dir. Should contain data files for WikiText." , ) parser.add_argument( "--model_name_or_path" , default=lowercase , type=lowercase , required=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--data_file" , type=lowercase , default=lowercase , help=( "A jbl file containing tokenized data which can be split as objective dataset, " "train_dataset and test_dataset." ) , ) parser.add_argument( "--igf_data_file" , type=lowercase , default=lowercase , help="A jbl file containing the context and information gain pairs to train secondary learner." , ) parser.add_argument( "--output_dir" , default=lowercase , type=lowercase , required=lowercase , help="The output directory where the final fine-tuned model is stored." , ) parser.add_argument( "--tokenizer_name" , default=lowercase , type=lowercase , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument("--seed" , type=lowercase , default=lowercase , help="A seed for reproducible training." ) parser.add_argument( "--context_len" , default=32 , type=lowercase , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--size_objective_set" , default=100 , type=lowercase , help="number of articles that are long enough to be used as our objective set" , ) parser.add_argument( "--eval_freq" , default=100 , type=lowercase , help="secondary model evaluation is triggered at eval_freq" ) parser.add_argument("--max_steps" , default=1000 , type=lowercase , help="To calculate training epochs" ) parser.add_argument( "--secondary_learner_batch_size" , default=128 , type=lowercase , help="batch size of training data for secondary learner" , ) parser.add_argument( "--batch_size" , default=16 , type=lowercase , help="batch size of training data of language model(gpt2) " ) parser.add_argument( "--eval_interval" , default=10 , type=lowercase , help=( "decay the selectivity of our secondary learner filter from" "1 standard deviation above average to 1 below average after 10 batches" ) , ) parser.add_argument( "--number" , default=100 , type=lowercase , help="The number of examples split to be used as objective_set/test_data" ) parser.add_argument( "--min_len" , default=1026 , type=lowercase , help="The minimum length of the article to be used as objective set" ) parser.add_argument( "--secondary_learner_max_epochs" , default=15 , type=lowercase , help="number of epochs to train secondary learner" ) parser.add_argument("--trim" , default=lowercase , type=lowercase , help="truncate the example if it exceeds context length" ) parser.add_argument( "--threshold" , default=1.0 , type=lowercase , help=( "The threshold value used by secondary learner to filter the train_data and allow only" " informative data as input to the model" ) , ) parser.add_argument("--finetuned_model_name" , default="gpt2_finetuned.pt" , type=lowercase , help="finetuned_model_name" ) parser.add_argument( "--recopy_model" , default=lowercase , type=lowercase , help="Reset the model to the original pretrained GPT-2 weights after each iteration" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=lowercase , data_file="data/tokenized_stories_train_wikitext103.jbl" , igf_data_file="igf_context_pairs.jbl" , ) # Load train data for secondary learner _a = joblib.load("data/IGF_values.jbl" ) # Train secondary learner _a = training_secondary_learner( lowercase , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="igf_model.pt" , ) # load pretrained gpt2 model _a = GPTaLMHeadModel.from_pretrained("gpt2" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _a , _a = generate_datasets( context_len=32 , file="data/tokenized_stories_train_wikitext103.jbl" , number=100 , min_len=1026 , trim=lowercase ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( lowercase , lowercase , lowercase , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=lowercase , secondary_learner=lowercase , eval_interval=10 , finetuned_model_name="gpt2_finetuned.pt" , ) if __name__ == "__main__": main()
350
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: _a = 10 _a = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) _a = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(lowercase ) ), } , features=lowercase , ) return dataset @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=lowercase ) return filename # FILE_CONTENT + files lowerCAmelCase_ : Union[str, Any] = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = tmp_path_factory.mktemp("data" ) / "file.txt" _a = FILE_CONTENT with open(lowercase , "w" ) as f: f.write(lowercase ) return filename @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: import bza _a = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" _a = bytes(lowercase , "utf-8" ) with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Optional[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) _a = bytes(lowercase , "utf-8" ) with gzip.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Union[str, Any]: if datasets.config.LZ4_AVAILABLE: import lza.frame _a = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" _a = bytes(lowercase , "utf-8" ) with lza.frame.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Tuple ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _a = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(lowercase , "w" ) as archive: archive.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Optional[Any] ) -> Dict: import tarfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any ) -> Union[str, Any]: import lzma _a = tmp_path_factory.mktemp("data" ) / "file.txt.xz" _a = bytes(lowercase , "utf-8" ) with lzma.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int , lowercase : Any ) -> Union[str, Any]: import zipfile _a = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> List[str]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _a = tmp_path_factory.mktemp("data" ) / "file.txt.zst" _a = bytes(lowercase , "utf-8" ) with zstd.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "file.xml" _a = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(lowercase , "w" ) as f: f.write(lowercase ) return filename lowerCAmelCase_ : Optional[int] = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] lowerCAmelCase_ : Dict = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } lowerCAmelCase_ : Dict = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] lowerCAmelCase_ : List[Any] = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> str: _a = datasets.Dataset.from_dict(lowercase ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict ) -> Dict: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(lowercase ) ) as con: _a = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(lowercase , "w" , newline="" ) as f: _a = csv.DictWriter(lowercase , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> int: import bza _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(lowercase , "rb" ) as f: _a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Any , lowercase : Any ) -> List[str]: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : Any , lowercase : List[Any] ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(lowercase , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Optional[Any] , lowercase : int ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) _a = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(lowercase , "wb" ) as f: _a = pq.ParquetWriter(lowercase , schema=lowercase ) _a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase ) )] for k in DATA[0]} , schema=lowercase ) writer.write_table(lowercase ) writer.close() return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) _a = {"data": DATA_DICT_OF_LISTS} with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] ) -> str: _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> List[str]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[Any] ) -> Optional[Any]: _a = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_312: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> int: _a = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(lowercase , "w" ) as f: for item in DATA_STR: f.write(json.dumps(lowercase ) + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[str] , lowercase : Dict ) -> Tuple: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : List[Any] ) -> List[Any]: import gzip _a = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(lowercase , "rb" ) as orig_file: with gzip.open(lowercase , "wb" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[Any] , lowercase : int ) -> str: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : int , lowercase : List[Any] ) -> Optional[int]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] , lowercase : str ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : Any , lowercase : Optional[int] ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str , lowercase : List[str] , lowercase : Union[str, Any] , lowercase : Union[str, Any] ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(lowercase , "w" ) as f: f.add(lowercase , arcname=os.path.join("nested" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : int ) -> str: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> Dict: _a = ["0", "1", "2", "3"] _a = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Dict: _a = ["0", "1", "2", "3"] _a = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(lowercase , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : Union[str, Any] , lowercase : Any ) -> Optional[Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Dict , lowercase : List[str] , lowercase : List[str] ) -> Union[str, Any]: _a = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("main_dir" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Tuple , lowercase : int , lowercase : str ) -> int: _a = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename("unsupported.ext" ) ) f.write(lowercase , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : List[Any] ) -> Any: _a = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) _a = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(lowercase , "w" , encoding="utf-8" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[Any]: return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( ) -> Optional[int]: return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> Dict: _a = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(lowercase , "w" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def _lowerCamelCase ( lowercase : str ) -> str: _a = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
346
0
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase_ : str = {'vocab_file': 'vocab.json'} lowerCAmelCase_ : List[str] = { 'vocab_file': { 'mgp-str': 'https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json', } } lowerCAmelCase_ : List[str] = {'mgp-str': 27} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __a : Tuple , __a : Dict="[GO]" , __a : List[str]="[GO]" , __a : Optional[Any]="[s]" , __a : Optional[Any]="[GO]" , **__a : Optional[Any] ): super().__init__( unk_token=__a , bos_token=__a , eos_token=__a , pad_token=__a , **__a , ) with open(__a , encoding="utf-8" ) as vocab_handle: _a = json.load(__a ) _a = {v: k for k, v in self.vocab.items()} @property def UpperCamelCase__ ( self : Union[str, Any] ): return len(self.vocab ) def UpperCamelCase__ ( self : int ): return dict(self.vocab , **self.added_tokens_encoder ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = [] for s in text: char_tokens.extend(__a ) return char_tokens def UpperCamelCase__ ( self : int , __a : Optional[Any] ): return self.vocab.get(__a , self.vocab.get(self.unk_token ) ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): if not os.path.isdir(__a ): logger.error("Vocabulary path ({}) should be a directory".format(__a ) ) return _a = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__a , ensure_ascii=__a ) + "\n" ) return (vocab_file,)
351
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='LayoutLMv2ImageProcessor' __a =('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Dict , __a : int=None , __a : List[Any]=None , **__a : str ): if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self : Optional[int] , __a : Optional[Any] , __a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __a : Union[List[List[int]], List[List[List[int]]]] = None , __a : Optional[Union[List[int], List[List[int]]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = None , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Optional[Any] , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor _a = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): _a = [text] # add batch dimension (as the image processor always adds a batch dimension) _a = features["words"] _a = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values _a = features.pop("pixel_values" ) if return_overflowing_tokens is True: _a = self.get_overflowing_images(__a , encoded_inputs["overflow_to_sample_mapping"] ) _a = images return encoded_inputs def UpperCamelCase__ ( self : int , __a : List[Any] , __a : int ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(__a )} and {len(__a )}' ) return images_with_overflow def UpperCamelCase__ ( self : Optional[Any] , *__a : Dict , **__a : Union[str, Any] ): return self.tokenizer.batch_decode(*__a , **__a ) def UpperCamelCase__ ( self : Union[str, Any] , *__a : Optional[int] , **__a : Optional[Any] ): return self.tokenizer.decode(*__a , **__a ) @property def UpperCamelCase__ ( self : int ): return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase__ ( self : List[Any] ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , ) return self.image_processor_class @property def UpperCamelCase__ ( self : int ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , ) return self.image_processor
346
0
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split lowerCAmelCase_ : str = datasets.load_iris() lowerCAmelCase_ : Any = np.array(data['data']) lowerCAmelCase_ : Union[str, Any] = np.array(data['target']) lowerCAmelCase_ : int = data['target_names'] lowerCAmelCase_ : str = train_test_split(X, y) def _lowerCamelCase ( lowercase : Tuple , lowercase : Union[str, Any] ) -> List[Any]: return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Union[str, Any] , lowercase : List[str] , lowercase : List[str]=5 ) -> Dict: _a = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified _a = [] for data_point in data: _a = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. _a = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified _a = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
352
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : int = '▁' lowerCAmelCase_ : Optional[Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : Union[str, Any] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['input_ids', 'attention_mask'] __a =[] def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Any="<s>" , __a : List[str]="</s>" , __a : str="<pad>" , __a : List[str]="<unk>" , __a : Union[str, Any]=False , __a : Any=False , __a : List[str]=None , __a : Optional[int]=None , __a : Optional[Dict[str, Any]] = None , **__a : int , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = do_upper_case _a = do_lower_case _a = load_json(__a ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__a , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : str ): return len(self.encoder ) @property def UpperCamelCase__ ( self : str ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : Optional[int] , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : Dict , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : List[str] , __a : Any ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a , self.unk_token ) def UpperCamelCase__ ( self : str , __a : List[str] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__a ) _a = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : int , __a : Any , __a : int=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase__ ( self : Any , __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 ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): _a = Path(__a ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(lowercase , "r" ) as f: return json.load(lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> None: with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase , indent=2 )
346
0
'''simple docstring''' from math import factorial def _lowerCamelCase ( lowercase : int = 20 ) -> int: _a = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... _a = n // 2 return int(factorial(lowercase ) / (factorial(lowercase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: lowerCAmelCase_ : Optional[Any] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
353
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): _a = Rectangle(height=0.5 , width=0.5 ) _a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _a = [mem.copy() for i in range(6 )] _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = VGroup(__a , __a ).arrange(__a , buff=0 ) _a = Text("CPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__a ) _a = [mem.copy() for i in range(4 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("GPU" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) gpu.move_to([-1, -1, 0] ) self.add(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Model" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , buff=0.5 , aligned_edge=__a ) model.move_to([3, -1.0, 0] ) self.add(__a ) _a = [] for i, rect in enumerate(__a ): rect.set_stroke(__a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__a , buff=0.0 ) self.add(__a ) cpu_targs.append(__a ) _a = [mem.copy() for i in range(6 )] _a = VGroup(*__a ).arrange(__a , buff=0 ) _a = Text("Loaded Checkpoint" , font_size=24 ) _a = Group(__a , __a ).arrange(__a , aligned_edge=__a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) _a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _a = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__a , __a ) _a = MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) _a = MarkupText( f'Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__a ) , Write(__a ) ) self.play(Write(__a , run_time=1 ) , Create(__a , run_time=1 ) ) _a = [] _a = [] for i, rect in enumerate(__a ): _a = fill.copy().set_fill(__a , opacity=0.7 ) target.move_to(__a ) first_animations.append(GrowFromCenter(__a , run_time=1 ) ) _a = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__a , run_time=1.5 ) ) self.play(*__a ) self.play(*__a ) self.wait()
346
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='deberta-v2' def __init__( self : Dict , __a : List[str]=12_81_00 , __a : int=15_36 , __a : Tuple=24 , __a : Dict=24 , __a : Any=61_44 , __a : Optional[Any]="gelu" , __a : int=0.1 , __a : Any=0.1 , __a : Optional[Any]=5_12 , __a : int=0 , __a : Tuple=0.02 , __a : Tuple=1e-7 , __a : List[str]=False , __a : Tuple=-1 , __a : Dict=0 , __a : Tuple=True , __a : Dict=None , __a : int=0 , __a : Tuple="gelu" , **__a : Optional[Any] , ): super().__init__(**__a ) _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = initializer_range _a = relative_attention _a = max_relative_positions _a = pad_token_id _a = position_biased_input # Backwards compatibility if type(__a ) == str: _a = [x.strip() for x in pos_att_type.lower().split("|" )] _a = pos_att_type _a = vocab_size _a = layer_norm_eps _a = kwargs.get("pooler_hidden_size" , __a ) _a = pooler_dropout _a = pooler_hidden_act class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" @property def UpperCamelCase__ ( self : Tuple ): if self.task == "multiple-choice": _a = {0: "batch", 1: "choice", 2: "sequence"} else: _a = {0: "batch", 1: "sequence"} if self._config.type_vocab_size > 0: return OrderedDict( [("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis)] ) else: return OrderedDict([("input_ids", dynamic_axis), ("attention_mask", dynamic_axis)] ) @property def UpperCamelCase__ ( self : List[Any] ): return 12 def UpperCamelCase__ ( self : Tuple , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional["TensorType"] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , __a : "PreTrainedTokenizerBase" = None , ): _a = super().generate_dummy_inputs(preprocessor=__a , framework=__a ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
354
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase_ : Tuple = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = test_results.split(" " ) _a = 0 _a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _a = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = {} _a = None _a = False for line in failures_short_lines.split("\n" ): if re.search(r"_ \[doctest\]" , lowercase ): _a = True _a = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): _a = line _a = False return failures class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : str , __a : Dict ): _a = title _a = doc_test_results["time_spent"].split("," )[0] _a = doc_test_results["success"] _a = doc_test_results["failures"] _a = self.n_success + self.n_failures # Failures and success of the modeling tests _a = doc_test_results @property def UpperCamelCase__ ( self : int ): _a = [self._time_spent] _a = 0 for time in time_spent: _a = time.split(":" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__a ) == 1: _a = [0, 0, time_parts[0]] _a , _a , _a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds _a , _a , _a = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(__a )}h{int(__a )}m{int(__a )}s' @property def UpperCamelCase__ ( self : Optional[Any] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self : Optional[Any] ): return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : List[str] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : str ): _a = 40 _a = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__a , __a )} _a = "" for category, failures in category_failures.items(): if len(__a ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def UpperCamelCase__ ( self : List[str] ): _a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__a ) @staticmethod def UpperCamelCase__ ( ): _a = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(__a )} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=__a , ) def UpperCamelCase__ ( self : Tuple ): print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(self.payload )} ) ) _a = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else "All tests passed." _a = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=__a , ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : List[Any] , __a : Tuple , __a : int ): _a = "" for key, value in failures.items(): _a = value[:2_00] + " [Truncated]" if len(__a ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' _a = job_name _a = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: _a = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self : str ): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made." ) _a = self.doc_test_results.pop("job_link" ) self.doc_test_results.pop("failures" ) self.doc_test_results.pop("success" ) self.doc_test_results.pop("time_spent" ) _a = sorted(self.doc_test_results.items() , key=lambda __a : t[0] ) for job, job_result in sorted_dict: if len(job_result["failures"] ): _a = f'*Num failures* :{len(job_result["failed"] )} \n' _a = job_result["failures"] _a = self.get_reply_blocks(__a , __a , __a , text=__a ) print("Sending the following reply" ) print(json.dumps({"blocks": blocks} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=f'Results for {job}' , blocks=__a , thread_ts=self.thread_ts["ts"] , ) time.sleep(1 ) def _lowerCamelCase ( ) -> Any: _a = os.environ["GITHUB_RUN_ID"] _a = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _a = requests.get(lowercase ).json() _a = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) _a = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): _a = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , lowercase ) return {} def _lowerCamelCase ( lowercase : str ) -> Dict: _a = {} if os.path.exists(lowercase ): _a = os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase , lowercase ) , encoding="utf-8" ) as f: _a = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase , lowercase )}.' ) from e return _artifact def _lowerCamelCase ( ) -> str: class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str ): _a = name _a = [] def __str__( self : List[str] ): return self.name def UpperCamelCase__ ( self : str , __a : str ): self.paths.append({"name": self.name, "path": path} ) _a = {} _a = filter(os.path.isdir , os.listdir() ) for directory in directories: _a = directory if artifact_name not in _available_artifacts: _a = Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase_ : List[Any] = get_job_links() lowerCAmelCase_ : Any = retrieve_available_artifacts() lowerCAmelCase_ : List[str] = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase_ : Optional[Any] = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase_ : int = github_actions_job_links.get('run_doctests') lowerCAmelCase_ : Union[str, Any] = available_artifacts['doc_tests_gpu_test_reports'].paths[0] lowerCAmelCase_ : List[str] = retrieve_artifact(artifact_path['name']) if "stats" in artifact: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = handle_test_results(artifact['stats']) lowerCAmelCase_ : List[str] = failed lowerCAmelCase_ : Optional[Any] = success lowerCAmelCase_ : Tuple = time_spent[1:-1] + ', ' lowerCAmelCase_ : List[Any] = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): lowerCAmelCase_ : int = line.replace('FAILED ', '') lowerCAmelCase_ : Optional[int] = line.split()[0].replace('\n', '') if "::" in line: lowerCAmelCase_ , lowerCAmelCase_ : str = line.split('::') else: lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase_ : Union[str, Any] = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase_ : List[str] = all_failures[test] if test in all_failures else 'N/A' lowerCAmelCase_ : Optional[Any] = failure break lowerCAmelCase_ : Tuple = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
346
0
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCamelCase ( ) -> str: _a = 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=lowercase , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowercase , 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=lowercase ) return parser.parse_args() def _lowerCamelCase ( ) -> Optional[int]: _a = parse_args() # Import training_script as a module. _a = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _a = script_fpath.stem _a = importlib.import_module(lowercase ) # Patch sys.argv _a = [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()
355
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCamelCase ( ) -> str: _a = HfArgumentParser(lowercase ) _a = parser.parse_args_into_dataclasses()[0] _a = TensorFlowBenchmark(args=lowercase ) try: _a = parser.parse_args_into_dataclasses()[0] except ValueError as e: _a = "Arg --no_{0} is no longer used, please use --no-{0} instead." _a = " ".join(str(lowercase ).split(" " )[:-1] ) _a = "" _a = eval(str(lowercase ).split(" " )[-1] ) _a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowercase ) if len(lowercase ) > 0: _a = full_error_msg + begin_error_msg + str(lowercase ) raise ValueError(lowercase ) benchmark.run() if __name__ == "__main__": main()
346
0
'''simple docstring''' import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def _lowerCamelCase ( lowercase : str , lowercase : str , **lowercase : List[str] ) -> Dict: _a = AutoConfig.from_pretrained(lowercase , **lowercase ) _a = AutoModelForSeqaSeqLM.from_config(lowercase ) model.save_pretrained(lowercase ) AutoTokenizer.from_pretrained(lowercase ).save_pretrained(lowercase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
356
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ : Union[str, Any] = None try: import msvcrt except ImportError: lowerCAmelCase_ : Tuple = None try: import fcntl except ImportError: lowerCAmelCase_ : Optional[int] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ : Any = OSError # Data # ------------------------------------------------ lowerCAmelCase_ : Tuple = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] lowerCAmelCase_ : Optional[int] = '3.0.12' lowerCAmelCase_ : Tuple = None def _lowerCamelCase ( ) -> Optional[int]: global _logger _a = _logger or logging.getLogger(__name__ ) return _logger class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict , __a : Optional[Any] ): _a = lock_file return None def __str__( self : Any ): _a = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , __a : Optional[int] ): _a = lock return None def __enter__( self : str ): return self.lock def __exit__( self : List[Any] , __a : List[Any] , __a : Union[str, Any] , __a : Dict ): self.lock.release() return None class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : Union[str, Any] , __a : Optional[int]=-1 , __a : Tuple=None ): _a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long _a = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. _a = 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. _a = None # The default timeout value. _a = timeout # We use this lock primarily for the lock counter. _a = 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. _a = 0 return None @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file @property def UpperCamelCase__ ( self : List[Any] ): return self._timeout @timeout.setter def UpperCamelCase__ ( self : int , __a : List[Any] ): _a = float(__a ) return None def UpperCamelCase__ ( self : Dict ): raise NotImplementedError() def UpperCamelCase__ ( self : str ): raise NotImplementedError() @property def UpperCamelCase__ ( self : Optional[Any] ): return self._lock_file_fd is not None def UpperCamelCase__ ( self : int , __a : int=None , __a : Tuple=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: _a = 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 _a = id(self ) _a = self._lock_file _a = 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(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: _a = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: _a = id(self ) _a = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() _a = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : List[Any] ): self.acquire() return self def __exit__( self : str , __a : str , __a : Dict , __a : Dict ): self.release() return None def __del__( self : int ): self.release(force=__a ) return None def UpperCamelCase__ ( self : Tuple , __a : str , __a : int ): _a = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: _a = os.path.dirname(__a ) _a = str(hash(__a ) ) _a = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , __a : str , __a : List[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) _a = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def UpperCamelCase__ ( self : int ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Optional[Any] ): _a = self._lock_file_fd _a = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=-1 , __a : int=None ): _a = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def UpperCamelCase__ ( self : Any ): _a = os.O_RDWR | os.O_CREAT | os.O_TRUNC _a = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: _a = fd return None def UpperCamelCase__ ( self : Tuple ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition _a = self._lock_file_fd _a = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): _a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: _a = os.open(self._lock_file , __a ) except OSError: pass else: _a = fd return None def UpperCamelCase__ ( self : Union[str, Any] ): os.close(self._lock_file_fd ) _a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ : str = None if msvcrt: lowerCAmelCase_ : List[str] = WindowsFileLock elif fcntl: lowerCAmelCase_ : List[str] = UnixFileLock else: lowerCAmelCase_ : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
346
0
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
357
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 # [batch_size x 3] __a =42 __a =42 __a =42 __a =42 __a =42 def UpperCamelCase__ ( self : str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase__ ( self : List[str] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = torch.arange(self.height * self.width ) _a = torch.stack( [ pixel_indices % self.width, torch.div(__a , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def UpperCamelCase__ ( self : List[Any] ): _a , *_a = self.shape _a = int(np.prod(__a ) ) _a = self.get_image_coords() _a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) _a = self.get_camera_rays(__a ) _a = rays.view(__a , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase__ ( self : Dict , __a : torch.Tensor ): _a , *_a , _a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] _a = coords.view(__a , -1 , 2 ) _a = self.resolution() _a = self.fov() _a = (flat.float() / (res - 1)) * 2 - 1 _a = fracs * torch.tan(fov / 2 ) _a = fracs.view(__a , -1 , 2 ) _a = ( self.z.view(__a , 1 , 3 ) + self.x.view(__a , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__a , 1 , 3 ) * fracs[:, :, 1:] ) _a = directions / directions.norm(dim=-1 , keepdim=__a ) _a = torch.stack( [ torch.broadcast_to(self.origin.view(__a , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__a , *__a , 2 , 3 ) def UpperCamelCase__ ( self : Dict , __a : int , __a : int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__a , height=__a , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase ( lowercase : int ) -> DifferentiableProjectiveCamera: _a = [] _a = [] _a = [] _a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): _a = np.array([np.sin(lowercase ), np.cos(lowercase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) _a = -z * 4 _a = np.array([np.cos(lowercase ), -np.sin(lowercase ), 0.0] ) _a = np.cross(lowercase , lowercase ) origins.append(lowercase ) xs.append(lowercase ) ys.append(lowercase ) zs.append(lowercase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase , axis=0 ) ).float() , width=lowercase , height=lowercase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase )) , )
346
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Tuple=13 , __a : Optional[Any]=7 , __a : Dict=True , __a : Tuple=True , __a : List[str]=True , __a : List[str]=True , __a : Optional[int]=True , __a : Optional[Any]=False , __a : Union[str, Any]=False , __a : List[str]=False , __a : str=2 , __a : str=99 , __a : List[Any]=0 , __a : List[Any]=32 , __a : Dict=5 , __a : Tuple=4 , __a : Dict=0.1 , __a : Optional[int]=0.1 , __a : Tuple=5_12 , __a : int=12 , __a : int=2 , __a : str=0.02 , __a : int=3 , __a : Dict=4 , __a : Dict="last" , __a : List[Any]=None , __a : Tuple=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_lengths _a = use_token_type_ids _a = use_labels _a = gelu_activation _a = sinusoidal_embeddings _a = causal _a = asm _a = n_langs _a = vocab_size _a = n_special _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = summary_type _a = use_proj _a = scope def UpperCamelCase__ ( self : List[str] ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None if self.use_input_lengths: _a = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , 2 ).float() _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCamelCase__ ( self : Tuple ): return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def UpperCamelCase__ ( self : List[Any] , __a : List[str] , __a : Optional[Any] , __a : Optional[Any] , __a : Tuple , __a : Optional[int] , __a : List[Any] , __a : Any , __a : int , __a : Optional[int] , ): _a = FlaubertModel(config=__a ) model.to(__a ) model.eval() _a = model(__a , lengths=__a , langs=__a ) _a = model(__a , langs=__a ) _a = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : Union[str, Any] , __a : Dict , __a : Optional[int] , __a : str , __a : Dict , __a : Optional[int] , __a : str , __a : Union[str, Any] , ): _a = FlaubertWithLMHeadModel(__a ) model.to(__a ) model.eval() _a = model(__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self : Dict , __a : Any , __a : Any , __a : int , __a : int , __a : Dict , __a : List[str] , __a : List[Any] , __a : Any , __a : str , ): _a = FlaubertForQuestionAnsweringSimple(__a ) model.to(__a ) model.eval() _a = model(__a ) _a = model(__a , start_positions=__a , end_positions=__a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self : Union[str, Any] , __a : List[str] , __a : Optional[int] , __a : str , __a : Tuple , __a : List[Any] , __a : List[str] , __a : Tuple , __a : Any , __a : Optional[int] , ): _a = FlaubertForQuestionAnswering(__a ) model.to(__a ) model.eval() _a = model(__a ) _a = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , p_mask=__a , ) _a = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , ) ((_a ) , ) = result_with_labels.to_tuple() _a = model(__a , start_positions=__a , end_positions=__a ) ((_a ) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCamelCase__ ( self : str , __a : List[Any] , __a : Union[str, Any] , __a : Optional[int] , __a : Any , __a : Dict , __a : List[Any] , __a : Optional[int] , __a : int , __a : Dict , ): _a = FlaubertForSequenceClassification(__a ) model.to(__a ) model.eval() _a = model(__a ) _a = model(__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ ( self : str , __a : Optional[int] , __a : List[str] , __a : List[str] , __a : Optional[Any] , __a : Tuple , __a : List[str] , __a : List[Any] , __a : int , __a : Dict , ): _a = self.num_labels _a = FlaubertForTokenClassification(__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple , __a : Any , __a : Tuple , __a : List[Any] , __a : Optional[Any] , __a : Optional[int] , __a : Any , __a : Union[str, Any] , __a : Optional[Any] , ): _a = self.num_choices _a = FlaubertForMultipleChoice(config=__a ) model.to(__a ) model.eval() _a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self : int ): _a = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) = config_and_inputs _a = { "input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths, "attention_mask": input_mask, } return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) __a =( { 'feature-extraction': FlaubertModel, 'fill-mask': FlaubertWithLMHeadModel, 'question-answering': FlaubertForQuestionAnsweringSimple, 'text-classification': FlaubertForSequenceClassification, 'token-classification': FlaubertForTokenClassification, 'zero-shot': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : Any , __a : Union[str, Any] , __a : Dict , __a : List[str] ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCamelCase__ ( self : Dict , __a : str , __a : int , __a : List[str]=False ): _a = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def UpperCamelCase__ ( self : Optional[Any] ): _a = FlaubertModelTester(self ) _a = ConfigTester(self , config_class=__a , emb_dim=37 ) def UpperCamelCase__ ( self : List[str] ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : Optional[int] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__a ) def UpperCamelCase__ ( self : str ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__a ) def UpperCamelCase__ ( self : Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__a ) def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__a ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__a ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__a ) @slow def UpperCamelCase__ ( self : List[Any] ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = FlaubertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @slow @require_torch_gpu def UpperCamelCase__ ( self : Any ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return _a = True _a = model_class(config=__a ) _a = self._prepare_for_class(__a , __a ) _a = torch.jit.trace( __a , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__a , os.path.join(__a , "traced_model.pt" ) ) _a = torch.jit.load(os.path.join(__a , "traced_model.pt" ) , map_location=__a ) loaded(inputs_dict["input_ids"].to(__a ) , inputs_dict["attention_mask"].to(__a ) ) @require_torch class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : List[Any] ): _a = FlaubertModel.from_pretrained("flaubert/flaubert_base_cased" ) _a = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) with torch.no_grad(): _a = model(__a )[0] _a = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , __a ) _a = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) )
358
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ : List[str] = TypeVar('T') lowerCAmelCase_ : Dict = TypeVar('U') class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Union[str, Any] , __a : T | None , __a : U | None ): _a = key _a = val _a = None _a = None def __repr__( self : Any ): return ( f'Node: key: {self.key}, val: {self.val}, ' f'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" def __init__( self : Dict ): _a = DoubleLinkedListNode(__a , __a ) _a = DoubleLinkedListNode(__a , __a ) _a , _a = self.rear, self.head def __repr__( self : str ): _a = ["DoubleLinkedList"] _a = self.head while node.next is not None: rep.append(str(__a ) ) _a = node.next rep.append(str(self.rear ) ) return ",\n ".join(__a ) def UpperCamelCase__ ( self : int , __a : DoubleLinkedListNode[T, U] ): _a = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _a = node _a = previous _a = node _a = self.rear def UpperCamelCase__ ( self : Any , __a : DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None _a = node.next _a = node.prev _a = None _a = None return node class __SCREAMING_SNAKE_CASE (Generic[T, U] ): """simple docstring""" __a ={} def __init__( self : Union[str, Any] , __a : int ): _a = DoubleLinkedList() _a = capacity _a = 0 _a = 0 _a = 0 _a = {} def __repr__( self : Optional[int] ): return ( f'CacheInfo(hits={self.hits}, misses={self.miss}, ' f'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self : str , __a : T ): return key in self.cache def UpperCamelCase__ ( self : str , __a : T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _a = self.cache[key] _a = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(__a ) return node.val self.miss += 1 return None def UpperCamelCase__ ( self : Tuple , __a : T , __a : U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _a = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(__a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _a = DoubleLinkedListNode(__a , __a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _a = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _a = value self.list.add(__a ) @classmethod def UpperCamelCase__ ( cls : Tuple , __a : int = 1_28 ): def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _a = LRUCache(__a ) _a = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _a = func(*__a ) cls.decorator_function_to_instance_map[func].put(args[0] , __a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(__a , "cache_info" , __a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Optional[int] = '\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n booktitle={ACL},\n year={2020},\n url={https://arxiv.org/abs/2004.04696}\n}\n' lowerCAmelCase_ : Any = '\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n' lowerCAmelCase_ : Dict = '\nBLEURT score.\n\nArgs:\n `predictions` (list of str): prediction/candidate sentences\n `references` (list of str): reference sentences\n `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n \'scores\': List of scores.\nExamples:\n\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> bleurt = datasets.load_metric("bleurt")\n >>> results = bleurt.compute(predictions=predictions, references=references)\n >>> print([round(v, 2) for v in results["scores"]])\n [1.03, 1.04]\n' lowerCAmelCase_ : Union[str, Any] = { 'bleurt-tiny-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip', 'bleurt-tiny-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip', 'bleurt-base-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip', 'bleurt-base-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip', 'bleurt-large-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip', 'bleurt-large-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip', 'BLEURT-20-D3': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip', 'BLEURT-20-D6': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip', 'BLEURT-20-D12': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip', 'BLEURT-20': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/google-research/bleurt" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/google-research/bleurt"] , reference_urls=["https://github.com/google-research/bleurt", "https://arxiv.org/abs/2004.04696"] , ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( "Using default BLEURT-Base checkpoint for sequence maximum length 128. " "You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512')." ) _a = "bleurt-base-128" if self.config_name.lower() in CHECKPOINT_URLS: _a = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: _a = self.config_name.upper() else: raise KeyError( f'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer _a = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) _a = score.BleurtScorer(os.path.join(__a , __a ) ) def UpperCamelCase__ ( self : str , __a : int , __a : str ): _a = self.scorer.score(references=__a , candidates=__a ) return {"scores": scores}
359
'''simple docstring''' import re from filelock import FileLock try: import nltk lowerCAmelCase_ : Optional[int] = True except (ImportError, ModuleNotFoundError): lowerCAmelCase_ : Tuple = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowerCamelCase ( lowercase : str ) -> str: re.sub("<n>" , "" , lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowercase ) )
346
0
'''simple docstring''' import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def _lowerCamelCase ( lowercase : Optional[Any] ) -> Optional[Any]: return x + 2 class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : List[str] ): _a = "x = 3" _a = {} _a = evaluate(__a , {} , state=__a ) assert result == 3 self.assertDictEqual(__a , {"x": 3} ) _a = "x = y" _a = {"y": 5} _a = evaluate(__a , {} , state=__a ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(__a , {"x": 5, "y": 5} ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = "y = add_two(x)" _a = {"x": 3} _a = evaluate(__a , {"add_two": add_two} , state=__a ) assert result == 5 self.assertDictEqual(__a , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: _a = evaluate(__a , {} , state=__a ) assert result is None assert "tried to execute add_two" in out.out def UpperCamelCase__ ( self : Tuple ): _a = "x = 3" _a = {} _a = evaluate(__a , {} , state=__a ) assert result == 3 self.assertDictEqual(__a , {"x": 3} ) def UpperCamelCase__ ( self : Dict ): _a = "test_dict = {'x': x, 'y': add_two(x)}" _a = {"x": 3} _a = evaluate(__a , {"add_two": add_two} , state=__a ) self.assertDictEqual(__a , {"x": 3, "y": 5} ) self.assertDictEqual(__a , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = "x = 3\ny = 5" _a = {} _a = evaluate(__a , {} , state=__a ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(__a , {"x": 3, "y": 5} ) def UpperCamelCase__ ( self : Optional[int] ): _a = "text = f'This is x: {x}.'" _a = {"x": 3} _a = evaluate(__a , {} , state=__a ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(__a , {"x": 3, "text": "This is x: 3."} ) def UpperCamelCase__ ( self : Optional[Any] ): _a = "if x <= 3:\n y = 2\nelse:\n y = 5" _a = {"x": 3} _a = evaluate(__a , {} , state=__a ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(__a , {"x": 3, "y": 2} ) _a = {"x": 8} _a = evaluate(__a , {} , state=__a ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(__a , {"x": 8, "y": 5} ) def UpperCamelCase__ ( self : Any ): _a = "test_list = [x, add_two(x)]" _a = {"x": 3} _a = evaluate(__a , {"add_two": add_two} , state=__a ) self.assertListEqual(__a , [3, 5] ) self.assertDictEqual(__a , {"x": 3, "test_list": [3, 5]} ) def UpperCamelCase__ ( self : str ): _a = "y = x" _a = {"x": 3} _a = evaluate(__a , {} , state=__a ) assert result == 3 self.assertDictEqual(__a , {"x": 3, "y": 3} ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = "test_list = [x, add_two(x)]\ntest_list[1]" _a = {"x": 3} _a = evaluate(__a , {"add_two": add_two} , state=__a ) assert result == 5 self.assertDictEqual(__a , {"x": 3, "test_list": [3, 5]} ) _a = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" _a = {"x": 3} _a = evaluate(__a , {"add_two": add_two} , state=__a ) assert result == 5 self.assertDictEqual(__a , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCamelCase__ ( self : Any ): _a = "x = 0\nfor i in range(3):\n x = i" _a = {} _a = evaluate(__a , {"range": range} , state=__a ) assert result == 2 self.assertDictEqual(__a , {"x": 2, "i": 2} )
360
'''simple docstring''' import requests lowerCAmelCase_ : List[Any] = 'YOUR API KEY' def _lowerCamelCase ( lowercase : str , lowercase : str = giphy_api_key ) -> list: _a = "+".join(query.split() ) _a = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' _a = requests.get(lowercase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
346
0
'''simple docstring''' from __future__ import annotations def _lowerCamelCase ( lowercase : list[int] , lowercase : int ) -> int: if len(lowercase ) < k or k < 0: raise ValueError("Invalid Input" ) _a = _a = sum(array[:k] ) for i in range(len(lowercase ) - k ): _a = current_sum - array[i] + array[i + k] _a = max(lowercase , lowercase ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() lowerCAmelCase_ : int = [randint(-10_00, 10_00) for i in range(1_00)] lowerCAmelCase_ : List[str] = randint(0, 1_10) print(f"""The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}""")
361
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =BertGenerationTokenizer __a =False __a =True def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() _a = BertGenerationTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ ( self : Tuple ): _a = "<s>" _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def UpperCamelCase__ ( self : List[str] ): _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(__a ) , 10_02 ) def UpperCamelCase__ ( self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def UpperCamelCase__ ( self : Tuple ): _a = BertGenerationTokenizer(__a , keep_accents=__a ) _a = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [2_85, 46, 10, 1_70, 3_82] , ) _a = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _a = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def UpperCamelCase__ ( self : Any ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def UpperCamelCase__ ( self : List[str] ): _a = "Hello World!" _a = [1_85_36, 22_60, 1_01] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def UpperCamelCase__ ( self : Optional[int] ): _a = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _a = [ 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def UpperCamelCase__ ( self : Tuple ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _a = list(self.big_tokenizer.get_vocab().keys() )[:10] _a = " ".join(__a ) _a = self.big_tokenizer.encode_plus(__a , return_tensors="pt" , return_token_type_ids=__a ) _a = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=__a ) _a = BertGenerationConfig() _a = BertGenerationEncoder(__a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def UpperCamelCase__ ( self : Optional[int] ): # fmt: off _a = {"input_ids": [[3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14], [4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
346
0
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : int = '▁' lowerCAmelCase_ : Optional[Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : Union[str, Any] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['input_ids', 'attention_mask'] __a =[] def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Any="<s>" , __a : List[str]="</s>" , __a : str="<pad>" , __a : List[str]="<unk>" , __a : Union[str, Any]=False , __a : Any=False , __a : List[str]=None , __a : Optional[int]=None , __a : Optional[Dict[str, Any]] = None , **__a : int , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = do_upper_case _a = do_lower_case _a = load_json(__a ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__a , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : str ): return len(self.encoder ) @property def UpperCamelCase__ ( self : str ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : Optional[int] , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : Dict , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : List[str] , __a : Any ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : str , __a : int ): return self.decoder.get(__a , self.unk_token ) def UpperCamelCase__ ( self : str , __a : List[str] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__a ) _a = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : int , __a : Any , __a : int=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase__ ( self : Any , __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 ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : str , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): _a = Path(__a ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(lowercase , "r" ) as f: return json.load(lowercase ) def _lowerCamelCase ( lowercase : Any , lowercase : str ) -> None: with open(lowercase , "w" ) as f: json.dump(lowercase , lowercase , indent=2 )
362
'''simple docstring''' def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Union[str, Any]: _enforce_args(lowercase , lowercase ) if n == 0: return 0 _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase ) ) return max_revue def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Tuple: _enforce_args(lowercase , lowercase ) _a = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase , lowercase , lowercase ) def _lowerCamelCase ( lowercase : int , lowercase : list , lowercase : list ) -> List[str]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _a = float("-inf" ) for i in range(1 , n + 1 ): _a = max( lowercase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase , lowercase ) , ) _a = max_revenue return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Any: _enforce_args(lowercase , lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _a = [float("-inf" ) for _ in range(n + 1 )] _a = 0 for i in range(1 , n + 1 ): _a = max_rev[i] for j in range(1 , i + 1 ): _a = max(lowercase , prices[j - 1] + max_rev[i - j] ) _a = max_revenue_i return max_rev[n] def _lowerCamelCase ( lowercase : int , lowercase : list ) -> Dict: if n < 0: _a = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): _a = ( "Each integral piece of rod must have a corresponding price. " F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def _lowerCamelCase ( ) -> Any: _a = [6, 10, 12, 15, 20, 23] _a = len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _a = 36 _a = top_down_cut_rod(lowercase , lowercase ) _a = bottom_up_cut_rod(lowercase , lowercase ) _a = naive_cut_rod_recursive(lowercase , lowercase ) 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()
346
0
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel lowerCAmelCase_ : Optional[Any] = HfApi() lowerCAmelCase_ : Optional[Any] = {} # fmt: off lowerCAmelCase_ : str = torch.tensor([ -0.7_515, -1.6_883, 0.2_420, 0.0_300, 0.6_347, 1.3_433, -1.1_743, -3.7_467, 1.2_342, -2.2_485, 0.4_636, 0.8_076, -0.7_991, 0.3_969, 0.8_498, 0.9_189, -1.8_887, -3.3_522, 0.7_639, 0.2_040, 0.6_271, -2.7_148, -1.6_316, 3.0_839, 0.3_186, 0.2_721, -0.9_759, -1.2_461, 2.6_257, 1.3_557 ]) lowerCAmelCase_ : List[Any] = torch.tensor([ -2.3_639, -2.5_344, 0.0_054, -0.6_674, 1.5_990, 1.0_158, 0.3_124, -2.1_436, 1.8_795, -2.5_429, -0.1_566, -0.3_973, 1.2_490, 2.6_447, 1.2_283, -0.5_208, -2.8_154, -3.5_119, 2.3_838, 1.2_033, 1.7_201, -2.1_256, -1.4_576, 2.7_948, 2.4_204, -0.9_752, -1.2_546, 0.8_027, 3.2_758, 3.1_365 ]) lowerCAmelCase_ : Tuple = torch.tensor([ -0.6_531, -0.6_891, -0.3_172, -0.5_375, -0.9_140, -0.5_367, -0.1_175, -0.7_869, -0.3_808, -0.4_513, -0.2_098, -0.0_083, 0.3_183, 0.5_140, 0.2_247, -0.1_304, -0.1_302, -0.2_802, -0.2_084, -0.2_025, -0.4_967, -0.4_873, -0.0_861, 0.6_925, 0.0_250, 0.1_290, -0.1_543, 0.6_316, 1.0_460, 1.4_943 ]) lowerCAmelCase_ : Optional[Any] = torch.tensor([ 0.0_911, 0.1_107, 0.0_182, 0.0_435, -0.0_805, -0.0_608, 0.0_381, 0.2_172, -0.0_280, 0.1_327, -0.0_299, -0.0_255, -0.0_050, -0.1_170, -0.1_046, 0.0_309, 0.1_367, 0.1_728, -0.0_533, -0.0_748, -0.0_534, 0.1_624, 0.0_384, -0.1_805, -0.0_707, 0.0_642, 0.0_220, -0.0_134, -0.1_333, -0.1_505 ]) lowerCAmelCase_ : Optional[Any] = torch.tensor([ 0.1_321, 0.1_337, 0.0_440, 0.0_622, -0.0_591, -0.0_370, 0.0_503, 0.2_133, -0.0_177, 0.1_415, -0.0_116, -0.0_112, 0.0_044, -0.0_980, -0.0_789, 0.0_395, 0.1_502, 0.1_785, -0.0_488, -0.0_514, -0.0_404, 0.1_539, 0.0_454, -0.1_559, -0.0_665, 0.0_659, 0.0_383, -0.0_005, -0.1_266, -0.1_386 ]) lowerCAmelCase_ : List[Any] = torch.tensor([ 0.1_154, 0.1_218, 0.0_307, 0.0_526, -0.0_711, -0.0_541, 0.0_366, 0.2_078, -0.0_267, 0.1_317, -0.0_226, -0.0_193, -0.0_014, -0.1_055, -0.0_902, 0.0_330, 0.1_391, 0.1_709, -0.0_562, -0.0_693, -0.0_560, 0.1_482, 0.0_381, -0.1_683, -0.0_681, 0.0_661, 0.0_331, -0.0_046, -0.1_268, -0.1_431 ]) lowerCAmelCase_ : List[Any] = torch.tensor([ 0.1_192, 0.1_240, 0.0_414, 0.0_606, -0.0_557, -0.0_412, 0.0_430, 0.2_042, -0.0_200, 0.1_385, -0.0_115, -0.0_132, 0.0_017, -0.0_965, -0.0_802, 0.0_398, 0.1_433, 0.1_747, -0.0_458, -0.0_533, -0.0_407, 0.1_545, 0.0_419, -0.1_574, -0.0_645, 0.0_626, 0.0_341, -0.0_010, -0.1_199, -0.1_390 ]) lowerCAmelCase_ : int = torch.tensor([ 0.1_075, 0.1_074, 0.0_205, 0.0_431, -0.0_774, -0.0_607, 0.0_298, 0.2_042, -0.0_320, 0.1_267, -0.0_281, -0.0_250, -0.0_064, -0.1_091, -0.0_946, 0.0_290, 0.1_328, 0.1_650, -0.0_580, -0.0_738, -0.0_586, 0.1_440, 0.0_337, -0.1_746, -0.0_712, 0.0_605, 0.0_250, -0.0_099, -0.1_316, -0.1_473 ]) lowerCAmelCase_ : Tuple = torch.tensor([ -1.4_572, -2.0_481, -0.0_414, -0.6_005, 1.4_136, 0.5_848, 0.4_028, -2.7_330, 1.2_212, -2.1_228, 0.2_155, 0.4_039, 0.7_662, 2.0_535, 0.7_477, -0.3_243, -2.1_758, -2.7_648, 1.6_947, 0.7_026, 1.2_338, -1.6_078, -0.8_682, 2.2_810, 1.8_574, -0.5_718, -0.5_586, -0.0_186, 2.3_415, 2.1_251]) lowerCAmelCase_ : Tuple = torch.tensor([ -1.3_690, -1.9_720, -0.4_090, -0.6_966, 1.4_660, 0.9_938, -0.1_385, -2.7_324, 0.7_736, -1.8_917, 0.2_923, 0.4_293, 0.1_693, 1.4_112, 1.1_887, -0.3_181, -2.2_160, -2.6_381, 1.3_170, 0.8_163, 0.9_240, -1.6_544, -0.6_099, 2.5_259, 1.6_430, -0.9_090, -0.9_392, -0.0_126, 2.4_268, 2.3_266 ]) lowerCAmelCase_ : int = torch.tensor([ -1.3_525, -1.9_628, -0.3_956, -0.6_860, 1.4_664, 1.0_014, -0.1_259, -2.7_212, 0.7_772, -1.8_811, 0.2_996, 0.4_388, 0.1_704, 1.4_029, 1.1_701, -0.3_027, -2.2_053, -2.6_287, 1.3_350, 0.8_131, 0.9_274, -1.6_292, -0.6_098, 2.5_131, 1.6_505, -0.8_958, -0.9_298, -0.0_151, 2.4_257, 2.3_355 ]) lowerCAmelCase_ : Optional[int] = torch.tensor([ -2.0_585, -2.7_897, -0.2_850, -0.8_940, 1.9_052, 0.5_702, 0.6_345, -3.8_959, 1.5_932, -3.2_319, 0.1_974, 0.0_287, 1.7_566, 2.6_543, 0.8_387, -0.5_351, -3.2_736, -4.3_375, 2.9_029, 1.6_390, 1.4_640, -2.1_701, -1.9_013, 2.9_341, 3.4_981, -0.6_255, -1.1_644, -0.1_591, 3.7_097, 3.2_066 ]) lowerCAmelCase_ : str = torch.tensor([ -2.3_139, -2.5_594, -0.0_197, -0.6_785, 1.7_001, 1.1_606, 0.3_075, -2.1_740, 1.8_071, -2.5_630, -0.0_926, -0.3_811, 1.2_116, 2.6_246, 1.2_731, -0.5_398, -2.8_153, -3.6_140, 2.3_893, 1.3_262, 1.6_258, -2.1_856, -1.3_267, 2.8_395, 2.3_779, -1.0_623, -1.2_468, 0.8_959, 3.3_367, 3.2_243 ]) lowerCAmelCase_ : Tuple = torch.tensor([ -2.0_628, -2.7_667, -0.2_089, -0.8_263, 2.0_539, 0.5_992, 0.6_495, -3.8_336, 1.6_025, -3.2_817, 0.1_721, -0.0_633, 1.7_516, 2.7_039, 0.8_100, -0.5_908, -3.2_113, -4.4_343, 2.9_257, 1.3_632, 1.5_562, -2.1_489, -1.9_894, 3.0_560, 3.3_396, -0.7_328, -1.0_417, 0.0_383, 3.7_093, 3.2_343 ]) lowerCAmelCase_ : Any = torch.tensor([ -1.4_574, -2.0_569, -0.0_473, -0.6_117, 1.4_018, 0.5_769, 0.4_129, -2.7_344, 1.2_241, -2.1_397, 0.2_000, 0.3_937, 0.7_616, 2.0_453, 0.7_324, -0.3_391, -2.1_746, -2.7_744, 1.6_963, 0.6_921, 1.2_187, -1.6_172, -0.8_877, 2.2_439, 1.8_471, -0.5_839, -0.5_605, -0.0_464, 2.3_250, 2.1_219 ]) # fmt: on lowerCAmelCase_ : str = api.list_models(filter='diffusers') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": lowerCAmelCase_ : Tuple = '/home/patrick/google_checkpoints/' + mod.modelId.split('/')[-1] print(f"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('CompVis'): lowerCAmelCase_ : str = UNetaDModel.from_pretrained(local_checkpoint, subfolder='unet') else: lowerCAmelCase_ : Optional[int] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) lowerCAmelCase_ : Tuple = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) lowerCAmelCase_ : List[str] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): lowerCAmelCase_ : List[str] = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['_'.join('_'.join(mod.modelId.split('/')).split('-'))], atol=1e-3 ) print(f"""{mod.modelId} has passed successfully!!!""")
363
'''simple docstring''' 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_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase_ ) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , *__a : Optional[int] , **__a : List[str] ): super().__init__(*__a , **__a ) self.check_model_type(__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : int=None , __a : Optional[Any]=None , **__a : List[Any] ): _a , _a = {}, {} if padding is not None: _a = padding if truncation is not None: _a = truncation if top_k is not None: _a = top_k return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , __a : Union["Image.Image", str] , __a : str = None , **__a : Any ): if isinstance(__a , (Image.Image, str) ) and isinstance(__a , __a ): _a = {"image": image, "question": question} else: _a = image _a = super().__call__(__a , **__a ) return results def UpperCamelCase__ ( self : Tuple , __a : Tuple , __a : Optional[Any]=False , __a : List[Any]=False ): _a = load_image(inputs["image"] ) _a = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=__a , truncation=__a ) _a = self.image_processor(images=__a , return_tensors=self.framework ) model_inputs.update(__a ) return model_inputs def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): _a = self.model(**__a ) return model_outputs def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : Dict=5 ): if top_k > self.model.config.num_labels: _a = self.model.config.num_labels if self.framework == "pt": _a = model_outputs.logits.sigmoid()[0] _a , _a = probs.topk(__a ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) _a = scores.tolist() _a = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__a , __a )]
346
0
'''simple docstring''' import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels lowerCAmelCase_ : Optional[int] = object() # For specifying empty leaf dict `{}` lowerCAmelCase_ : str = object() def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Optional[int] ) -> Tuple: _a = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(lowercase ) - len(lowercase ) + 1 ): _a = [x.match(lowercase ) for x, y in zip(lowercase , ks[i:] )] if matches and all(lowercase ): return True return False def _lowerCamelCase ( lowercase : Optional[Any] ) -> Union[str, Any]: def replace(lowercase : Optional[Any] , lowercase : List[Any] ): for rule, replacement in rules: if _match(lowercase , lowercase ): return replacement return val return replace def _lowerCamelCase ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , lowercase )), (("transformer", "wte", "embedding"), P("mp" , lowercase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowercase , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , lowercase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowercase , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , lowercase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCamelCase ( lowercase : Union[str, Any] ) -> Union[str, Any]: _a = _get_partition_rules() _a = _replacement_rules(lowercase ) _a = {k: _unmatched for k in flatten_dict(lowercase )} _a = {k: replace(lowercase , lowercase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowercase ) )
364
'''simple docstring''' from random import randint, random def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : bool = False , lowercase : int = 5 , ) -> list: _a = [[-1] * number_of_cells] # Create a highway without any car _a = 0 _a = max(lowercase , 0 ) while i < number_of_cells: _a = ( randint(0 , lowercase ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( lowercase : list , lowercase : int ) -> int: _a = 0 _a = highway_now[car_index + 1 :] for cell in range(len(lowercase ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(lowercase , -1 ) def _lowerCamelCase ( lowercase : list , lowercase : float , lowercase : int ) -> list: _a = len(lowercase ) # Beforce calculations, the highway is empty _a = [-1] * number_of_cells for car_index in range(lowercase ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed _a = min(highway_now[car_index] + 1 , lowercase ) # Number of empty cell before the next car _a = get_distance(lowercase , lowercase ) - 1 # We can't have the car causing an accident _a = min(next_highway[car_index] , lowercase ) if random() < probability: # Randomly, a driver will slow down _a = max(next_highway[car_index] - 1 , 0 ) return next_highway def _lowerCamelCase ( lowercase : list , lowercase : int , lowercase : float , lowercase : int ) -> list: _a = len(highway[0] ) for i in range(lowercase ): _a = update(highway[i] , lowercase , lowercase ) _a = [-1] * number_of_cells for car_index in range(lowercase ): _a = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) _a = (car_index + speed) % number_of_cells # Commit the change of position _a = speed highway.append(lowercase ) return highway if __name__ == "__main__": import doctest doctest.testmod()
346
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : List[str] = logging.get_logger(__name__) lowerCAmelCase_ : List[str] = { 'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='wavlm' def __init__( self : Union[str, Any] , __a : List[str]=32 , __a : Tuple=7_68 , __a : Union[str, Any]=12 , __a : Optional[Any]=12 , __a : str=30_72 , __a : Dict="gelu" , __a : int=0.1 , __a : List[str]=0.1 , __a : Optional[int]=0.1 , __a : Any=0.0 , __a : Optional[Any]=0.1 , __a : Optional[Any]=0.1 , __a : Any=0.02 , __a : List[Any]=1e-5 , __a : Tuple="group" , __a : Union[str, Any]="gelu" , __a : Any=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , __a : str=(5, 2, 2, 2, 2, 2, 2) , __a : List[Any]=(10, 3, 3, 3, 3, 2, 2) , __a : List[Any]=False , __a : List[Any]=1_28 , __a : Union[str, Any]=16 , __a : Union[str, Any]=3_20 , __a : Optional[Any]=8_00 , __a : Optional[Any]=False , __a : List[str]=True , __a : str=0.05 , __a : Tuple=10 , __a : str=2 , __a : List[str]=0.0 , __a : Dict=10 , __a : Optional[int]=3_20 , __a : Optional[Any]=2 , __a : int=0.1 , __a : int=1_00 , __a : str=2_56 , __a : List[str]=2_56 , __a : Union[str, Any]=0.1 , __a : Dict="mean" , __a : Tuple=False , __a : Optional[int]=False , __a : List[Any]=2_56 , __a : Optional[int]=(5_12, 5_12, 5_12, 5_12, 15_00) , __a : Optional[Any]=(5, 3, 3, 1, 1) , __a : int=(1, 2, 3, 1, 1) , __a : List[Any]=5_12 , __a : Dict=80 , __a : str=0 , __a : Tuple=1 , __a : Optional[int]=2 , __a : int=False , __a : List[str]=3 , __a : Any=2 , __a : Tuple=3 , __a : Dict=None , **__a : Tuple , ): 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_buckets _a = max_bucket_distance _a = num_conv_pos_embeddings _a = num_conv_pos_embedding_groups _a = len(self.conv_dim ) _a = num_hidden_layers _a = intermediate_size _a = hidden_act _a = num_attention_heads _a = hidden_dropout _a = attention_dropout _a = activation_dropout _a = feat_proj_dropout _a = final_dropout _a = layerdrop _a = layer_norm_eps _a = initializer_range _a = num_ctc_classes _a = vocab_size _a = do_stable_layer_norm _a = use_weighted_layer_sum _a = classifier_proj_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)`, but is `len(config.conv_dim) =" f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' f' `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 # parameters for pretraining with codevector quantized representations _a = num_codevectors_per_group _a = num_codevector_groups _a = contrastive_logits_temperature _a = num_negatives _a = codevector_dim _a = proj_codevector_dim _a = diversity_loss_weight # ctc loss _a = ctc_loss_reduction _a = ctc_zero_infinity # adapter _a = add_adapter _a = adapter_kernel_size _a = adapter_stride _a = num_adapter_layers _a = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _a = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _a = list(__a ) _a = list(__a ) _a = list(__a ) _a = xvector_output_dim @property def UpperCamelCase__ ( self : List[str] ): return functools.reduce(operator.mul , self.conv_stride , 1 )
365
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 10 ) -> str: if not isinstance(lowercase , lowercase ) or n < 0: raise ValueError("Invalid input" ) _a = 10**n _a = 2_8433 * (pow(2 , 783_0457 , lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
346
0
'''simple docstring''' from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowerCAmelCase_ : Tuple = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowerCAmelCase_ : Optional[Any] = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowerCAmelCase_ : List[Any] = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : Union[str, Any] ): 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 UpperCamelCase__ ( self : Tuple , __a : List[List[List[str]]] , __a : List[List[str]] , __a : int = 1 , __a : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=__a , hypotheses=__a , min_len=__a , max_len=__a ) }
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0