code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version snake_case_ = get_logger(__name__) class SCREAMING_SNAKE_CASE__ : '''simple docstring''' _A = "dummy_data" _A = "datasets" _A = False def __init__( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ = None , lowercase__ = False , lowercase__ = True , lowercase__ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = dataset_name SCREAMING_SNAKE_CASE_ : str = cache_dir SCREAMING_SNAKE_CASE_ : Tuple = use_local_dummy_data SCREAMING_SNAKE_CASE_ : int = config # download_callbacks take a single url as input SCREAMING_SNAKE_CASE_ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root SCREAMING_SNAKE_CASE_ : List[str] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general SCREAMING_SNAKE_CASE_ : Optional[int] = str(__a ) # to be downloaded SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None @property def __lowerCamelCase ( self ): """simple docstring""" if self._dummy_file is None: SCREAMING_SNAKE_CASE_ : Tuple = self.download_dummy_data() return self._dummy_file @property def __lowerCamelCase ( self ): """simple docstring""" if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def __lowerCamelCase ( self ): """simple docstring""" return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) SCREAMING_SNAKE_CASE_ : int = cached_path( __a , cache_dir=self.cache_dir , extract_compressed_file=__a , force_extract=__a ) return os.path.join(__a , self.dummy_file_name ) @property def __lowerCamelCase ( self ): """simple docstring""" return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCamelCase ( self ): """simple docstring""" if self._bucket_url is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def __lowerCamelCase ( self ): """simple docstring""" if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def __lowerCamelCase ( self , lowercase__ , *lowercase__ ): """simple docstring""" if self.load_existing_dummy_data: # dummy data is downloaded and tested SCREAMING_SNAKE_CASE_ : int = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned SCREAMING_SNAKE_CASE_ : Optional[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__a , __a ): return self.create_dummy_data_dict(__a , __a ) elif isinstance(__a , (list, tuple) ): return self.create_dummy_data_list(__a , __a ) else: return self.create_dummy_data_single(__a , __a ) def __lowerCamelCase ( self , lowercase__ , *lowercase__ ): """simple docstring""" return self.download_and_extract(__a ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" return self.download_and_extract(__a ) def __lowerCamelCase ( self , lowercase__ , *lowercase__ , **lowercase__ ): """simple docstring""" return path def __lowerCamelCase ( self ): """simple docstring""" return {} def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__a , __a ): for single_url in single_urls: download_callback(__a ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = single_urls download_callback(__a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Dict = [os.path.join(__a , urllib.parse.quote_plus(Path(__a ).name ) ) for x in single_urls] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = single_urls SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(__a , urllib.parse.quote_plus(Path(__a ).name ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = value # make sure that values are unique if all(isinstance(__a , __a ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique SCREAMING_SNAKE_CASE_ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one SCREAMING_SNAKE_CASE_ : int = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , __a ) ) for url in data_url ) SCREAMING_SNAKE_CASE_ : Any = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): SCREAMING_SNAKE_CASE_ : Optional[Any] = [data_url[0]] * len(__a ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(__a , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(__a ) return dummy_data_list def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" for download_callback in self.download_callbacks: download_callback(__a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(__a , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(__a ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" def _iter_archive_members(lowercase__ ): # this preserves the order of the members inside the ZIP archive SCREAMING_SNAKE_CASE_ : Optional[Any] = Path(self.dummy_file ).parent SCREAMING_SNAKE_CASE_ : int = path.relative_to(__a ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: SCREAMING_SNAKE_CASE_ : List[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__a ) SCREAMING_SNAKE_CASE_ : Tuple = Path(__a ) SCREAMING_SNAKE_CASE_ : int = _iter_archive_members(__a ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(__a ).as_posix(), file_path.open("rb" ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if not isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = [paths] for path in paths: if os.path.isfile(__a ): if os.path.basename(__a ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__a ): if os.path.basename(__a ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(__a ): if filename.startswith((".", "__") ): continue yield os.path.join(__a , __a )
717
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.5, 0.5, 0.5] , lowercase__=[0.5, 0.5, 0.5] , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = size if size is not None else {"shortest_edge": 18} SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : Dict = parent SCREAMING_SNAKE_CASE_ : List[str] = batch_size SCREAMING_SNAKE_CASE_ : List[str] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Dict = do_resize SCREAMING_SNAKE_CASE_ : Any = size SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop SCREAMING_SNAKE_CASE_ : int = crop_size SCREAMING_SNAKE_CASE_ : Tuple = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std def __lowerCamelCase ( self ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = LevitImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitImageProcessingTester(self ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A , "image_mean" ) ) self.assertTrue(hasattr(__A , "image_std" ) ) self.assertTrue(hasattr(__A , "do_normalize" ) ) self.assertTrue(hasattr(__A , "do_resize" ) ) self.assertTrue(hasattr(__A , "do_center_crop" ) ) self.assertTrue(hasattr(__A , "size" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A ) for image in image_inputs: self.assertIsInstance(__A , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : str = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(__A , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A ) for image in image_inputs: self.assertIsInstance(__A , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : List[Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
718
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
0
'''simple docstring''' from __future__ import annotations from typing import TypedDict class SCREAMING_SNAKE_CASE__ ( __snake_case ): _A = 42 _A = 42 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("The parameter s type must be str." ) return [s[i:] + s[:i] for i in range(len(_lowerCamelCase ) )] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("The parameter s type must be str." ) if not s: raise ValueError("The parameter s must not be empty." ) SCREAMING_SNAKE_CASE_ : int = all_rotations(_lowerCamelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation SCREAMING_SNAKE_CASE_ : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_lowerCamelCase ), } return response def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ) -> Any: """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("The parameter bwt_string type must be str." ) if not bwt_string: raise ValueError("The parameter bwt_string must not be empty." ) try: SCREAMING_SNAKE_CASE_ : int = int(_lowerCamelCase ) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0." ) if idx_original_string >= len(_lowerCamelCase ): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) SCREAMING_SNAKE_CASE_ : Tuple = [""""""] * len(_lowerCamelCase ) for _ in range(len(_lowerCamelCase ) ): for i in range(len(_lowerCamelCase ) ): SCREAMING_SNAKE_CASE_ : Optional[Any] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": snake_case_ : Optional[int] = 'Provide a string that I will generate its BWT transform: ' snake_case_ : List[str] = input(entry_msg).strip() snake_case_ : Union[str, Any] = bwt_transform(s) print( F'''Burrows Wheeler transform for string \'{s}\' results ''' F'''in \'{result["bwt_string"]}\'''' ) snake_case_ : str = reverse_bwt(result['bwt_string'], result['idx_original_string']) print( F'''Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ''' F'''we get original string \'{original_string}\'''' )
719
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
0
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device snake_case_ = False class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): pass @nightly @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = VersatileDiffusionTextToImagePipeline.from_pretrained("shi-labs/versatile-diffusion" ) # remove text_unet pipe.remove_unused_weights() pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) SCREAMING_SNAKE_CASE_ : str = """A painting of a squirrel eating a burger """ SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=A__ , generator=A__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(A__ ) SCREAMING_SNAKE_CASE_ : List[str] = VersatileDiffusionTextToImagePipeline.from_pretrained(A__ ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) SCREAMING_SNAKE_CASE_ : List[str] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=A__ , generator=A__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VersatileDiffusionTextToImagePipeline.from_pretrained( "shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) SCREAMING_SNAKE_CASE_ : List[str] = """A painting of a squirrel eating a burger """ SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Optional[int] = pipe( prompt=A__ , generator=A__ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
720
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
0
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class SCREAMING_SNAKE_CASE__ : @staticmethod def __lowerCamelCase ( *lowercase__ , **lowercase__ ): """simple docstring""" pass def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:1_0] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = np.array(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = npimg.shape return {"hash": hashimage(lowerCAmelCase__ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _A = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _A = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = MaskGenerationPipeline(model=_a , image_processor=_a ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def __lowerCamelCase ( self ): """simple docstring""" pass @slow @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = pipeline("mask-generation" , model="facebook/sam-vit-huge" ) SCREAMING_SNAKE_CASE_ : Tuple = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=256 ) # Shortening by hashing SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.0444}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.021}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.0167}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.0132}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.0053}, {"mask": {"hash": "e2d0b7a0b7", "shape": (480, 640)}, "scores": 0.9967}, {"mask": {"hash": "453c7844bd", "shape": (480, 640)}, "scores": 0.993}, {"mask": {"hash": "3d44f2926d", "shape": (480, 640)}, "scores": 0.9909}, {"mask": {"hash": "64033ddc3f", "shape": (480, 640)}, "scores": 0.9879}, {"mask": {"hash": "801064ff79", "shape": (480, 640)}, "scores": 0.9834}, {"mask": {"hash": "6172f276ef", "shape": (480, 640)}, "scores": 0.9716}, {"mask": {"hash": "b49e60e084", "shape": (480, 640)}, "scores": 0.9612}, {"mask": {"hash": "a811e775fd", "shape": (480, 640)}, "scores": 0.9599}, {"mask": {"hash": "a6a8ebcf4b", "shape": (480, 640)}, "scores": 0.9552}, {"mask": {"hash": "9d8257e080", "shape": (480, 640)}, "scores": 0.9532}, {"mask": {"hash": "32de6454a8", "shape": (480, 640)}, "scores": 0.9516}, {"mask": {"hash": "af3d4af2c8", "shape": (480, 640)}, "scores": 0.9499}, {"mask": {"hash": "3c6db475fb", "shape": (480, 640)}, "scores": 0.9483}, {"mask": {"hash": "c290813fb9", "shape": (480, 640)}, "scores": 0.9464}, {"mask": {"hash": "b6f0b8f606", "shape": (480, 640)}, "scores": 0.943}, {"mask": {"hash": "92ce16bfdf", "shape": (480, 640)}, "scores": 0.943}, {"mask": {"hash": "c749b25868", "shape": (480, 640)}, "scores": 0.9408}, {"mask": {"hash": "efb6cab859", "shape": (480, 640)}, "scores": 0.9335}, {"mask": {"hash": "1ff2eafb30", "shape": (480, 640)}, "scores": 0.9326}, {"mask": {"hash": "788b798e24", "shape": (480, 640)}, "scores": 0.9262}, {"mask": {"hash": "abea804f0e", "shape": (480, 640)}, "scores": 0.8999}, {"mask": {"hash": "7b9e8ddb73", "shape": (480, 640)}, "scores": 0.8986}, {"mask": {"hash": "cd24047c8a", "shape": (480, 640)}, "scores": 0.8984}, {"mask": {"hash": "6943e6bcbd", "shape": (480, 640)}, "scores": 0.8873}, {"mask": {"hash": "b5f47c9191", "shape": (480, 640)}, "scores": 0.8871} ] , ) # fmt: on @require_torch @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "facebook/sam-vit-huge" SCREAMING_SNAKE_CASE_ : Dict = pipeline("mask-generation" , model=_a ) SCREAMING_SNAKE_CASE_ : Tuple = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing SCREAMING_SNAKE_CASE_ : Dict = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.0444}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0210}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.0167}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.0132}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.0053}, ] , )
721
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
0
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , *lowercase__ , lowercase__=None , lowercase__=None , **lowercase__ ): """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Dict = eval_examples SCREAMING_SNAKE_CASE_ : Union[str, Any] = post_process_function def __lowerCamelCase ( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = "eval" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_eval_dataloader(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : int = self.compute_metrics SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : str = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop SCREAMING_SNAKE_CASE_ : List[str] = time.time() try: SCREAMING_SNAKE_CASE_ : Union[str, Any] = eval_loop( UpperCamelCase__ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , metric_key_prefix=UpperCamelCase__ , ) finally: SCREAMING_SNAKE_CASE_ : Any = compute_metrics SCREAMING_SNAKE_CASE_ : str = self.args.eval_batch_size * self.args.world_size if F"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[F"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( UpperCamelCase__ , UpperCamelCase__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE_ : List[str] = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions ) SCREAMING_SNAKE_CASE_ : int = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"{metric_key_prefix}_" ): SCREAMING_SNAKE_CASE_ : Optional[Any] = metrics.pop(UpperCamelCase__ ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE_ : Tuple = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(UpperCamelCase__ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCamelCase__ ) return metrics def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__ = "test" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_test_dataloader(UpperCamelCase__ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : Any = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop SCREAMING_SNAKE_CASE_ : Dict = time.time() try: SCREAMING_SNAKE_CASE_ : Dict = eval_loop( UpperCamelCase__ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , metric_key_prefix=UpperCamelCase__ , ) finally: SCREAMING_SNAKE_CASE_ : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE_ : List[Any] = self.args.eval_batch_size * self.args.world_size if F"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[F"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( UpperCamelCase__ , UpperCamelCase__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE_ : Optional[Any] = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE_ : Tuple = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"{metric_key_prefix}_" ): SCREAMING_SNAKE_CASE_ : Optional[Any] = metrics.pop(UpperCamelCase__ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCamelCase__ )
700
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
0
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] = 8 ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = ascii_letters + digits + punctuation return "".join(secrets.choice(SCREAMING_SNAKE_CASE_ ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" i -= len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = i // 3 SCREAMING_SNAKE_CASE_ : Tuple = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) SCREAMING_SNAKE_CASE_ : Tuple = ( chars_incl + random(SCREAMING_SNAKE_CASE_ , quotient + remainder ) + random(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) + random(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : List[str] = list(SCREAMING_SNAKE_CASE_ ) shuffle(SCREAMING_SNAKE_CASE_ ) return "".join(SCREAMING_SNAKE_CASE_ ) # random is a generalised function for letters, characters and numbers def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: """simple docstring""" return "".join(secrets.choice(SCREAMING_SNAKE_CASE_ ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Optional[Any]: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] ) -> int: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple ) -> Tuple: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int = 8 ) -> List[str]: """simple docstring""" if len(SCREAMING_SNAKE_CASE_ ) < min_length: # Your Password must be at least 8 characters long return False SCREAMING_SNAKE_CASE_ : int = any(char in ascii_uppercase for char in password ) SCREAMING_SNAKE_CASE_ : List[Any] = any(char in ascii_lowercase for char in password ) SCREAMING_SNAKE_CASE_ : Optional[Any] = any(char in digits for char in password ) SCREAMING_SNAKE_CASE_ : str = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def __lowerCamelCase ( ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = int(input("Please indicate the max length of your password: " ).strip() ) SCREAMING_SNAKE_CASE_ : List[Any] = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(SCREAMING_SNAKE_CASE_ ) ) print( "Alternative Password generated:" , alternative_password_generator(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
701
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: """simple docstring""" return getitem, k def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return setitem, k, v def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> List[str]: """simple docstring""" return delitem, k def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] , *SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: """simple docstring""" try: return fun(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ), None except Exception as e: return None, e snake_case_ = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) snake_case_ = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] snake_case_ = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] snake_case_ = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] snake_case_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] snake_case_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = HashMap(initial_block_size=4 ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} for _, (fun, *args) in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = _run_operation(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = _run_operation(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) assert my_res == py_res assert str(SCREAMING_SNAKE_CASE_ ) == str(SCREAMING_SNAKE_CASE_ ) assert set(SCREAMING_SNAKE_CASE_ ) == set(SCREAMING_SNAKE_CASE_ ) assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) assert set(my.items() ) == set(py.items() ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" def is_public(SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> bool: return not name.startswith("_" ) SCREAMING_SNAKE_CASE_ : Any = {name for name in dir({} ) if is_public(SCREAMING_SNAKE_CASE_ )} SCREAMING_SNAKE_CASE_ : Union[str, Any] = {name for name in dir(HashMap() ) if is_public(SCREAMING_SNAKE_CASE_ )} assert dict_public_names > hash_public_names
702
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin snake_case_ = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right snake_case_ = 2_5_0_0_0_4 snake_case_ = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __A,unittest.TestCase ): _A = MBartTokenizer _A = MBartTokenizerFast _A = True _A = True def __lowerCamelCase ( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ : Any = MBartTokenizer(lowercase__ , keep_accents=lowercase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = MBartTokenizer(lowercase__ , keep_accents=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowercase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.convert_tokens_to_ids(lowercase__ ) self.assertListEqual( lowercase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE_ : Any = tokenizer.convert_ids_to_tokens(lowercase__ ) self.assertListEqual( lowercase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def __lowerCamelCase ( self ): """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE_ : Tuple = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Dict = tokenizer_r.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_p.save_pretrained(lowercase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE_ : Tuple = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(lowercase__ , lowercase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_ : Any = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase__ ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE_ : Optional[int] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : str = tokenizer_r.save_pretrained(lowercase__ , legacy_format=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_p.save_pretrained(lowercase__ ) # Checks it save with the same files self.assertSequenceEqual(lowercase__ , lowercase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) shutil.rmtree(lowercase__ ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE_ : Optional[int] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_r.save_pretrained(lowercase__ , legacy_format=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer_p.save_pretrained(lowercase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_ : int = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) shutil.rmtree(lowercase__ ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _A = "facebook/mbart-large-en-ro" _A = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] _A = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] _A = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __lowerCamelCase ( cls ): """simple docstring""" SCREAMING_SNAKE_CASE_ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) SCREAMING_SNAKE_CASE_ : int = 1 return cls def __lowerCamelCase ( self ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_0020 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" self.assertIn(lowercase__ , self.tokenizer.all_special_ids ) SCREAMING_SNAKE_CASE_ : Optional[int] = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] SCREAMING_SNAKE_CASE_ : int = self.tokenizer.decode(lowercase__ , skip_special_tokens=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowercase__ ) self.assertEqual(lowercase__ , lowercase__ ) self.assertNotIn(self.tokenizer.eos_token , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = 10 SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase__ , max_length=lowercase__ , truncation=lowercase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , lowercase__ ) self.assertEqual(len(lowercase__ ) , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_0026, 25_0001] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = MBartTokenizer.from_pretrained(lowercase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowercase__ ) @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowercase__ , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : int = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowercase__ , truncation=lowercase__ , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) SCREAMING_SNAKE_CASE_ : Optional[int] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowercase__ , lowercase__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE_ : Dict = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowercase__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.tokenizer(self.src_text , padding=lowercase__ , truncation=lowercase__ , max_length=3 , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer( text_target=self.tgt_text , padding=lowercase__ , truncation=lowercase__ , max_length=10 , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : List[str] = targets['input_ids'] SCREAMING_SNAKE_CASE_ : Dict = shift_tokens_right(lowercase__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(lowercase__ ) , { # A, test, EOS, en_XX "input_ids": [[62, 3034, 2, 25_0004]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_0001, } , )
703
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
0
'''simple docstring''' import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa snake_case_ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE__ ( __lowercase ): _A = "summarization" _A = ["loss"] _A = ROUGE_KEYS _A = "rouge2" def __init__( self , lowercase__ , **lowercase__ ): """simple docstring""" if hparams.sortish_sampler and hparams.gpus > 1: SCREAMING_SNAKE_CASE_ : Union[str, Any] = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError("Dynamic Batch size does not work for multi-gpu training" ) if hparams.sortish_sampler: raise ValueError("--sortish_sampler and --max_tokens_per_batch may not be used simultaneously" ) super().__init__(_A , num_labels=_A , mode=self.mode , **_A ) use_task_specific_params(self.model , "summarization" ) save_git_info(self.hparams.output_dir ) SCREAMING_SNAKE_CASE_ : Dict = Path(self.output_dir ) / "metrics.json" SCREAMING_SNAKE_CASE_ : Optional[Any] = Path(self.output_dir ) / "hparams.pkl" pickle_save(self.hparams , self.hparams_save_path ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Dict = defaultdict(_A ) SCREAMING_SNAKE_CASE_ : Dict = self.config.model_type SCREAMING_SNAKE_CASE_ : Dict = self.config.tgt_vocab_size if self.model_type == "fsmt" else self.config.vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = { "data_dir": self.hparams.data_dir, "max_source_length": self.hparams.max_source_length, "prefix": self.model.config.prefix or "", } SCREAMING_SNAKE_CASE_ : Optional[int] = { "train": self.hparams.n_train, "val": self.hparams.n_val, "test": self.hparams.n_test, } SCREAMING_SNAKE_CASE_ : Tuple = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} SCREAMING_SNAKE_CASE_ : Optional[Any] = { "train": self.hparams.max_target_length, "val": self.hparams.val_max_target_length, "test": self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], F"target_lens: {self.target_lens}" assert self.target_lens["train"] <= self.target_lens["test"], F"target_lens: {self.target_lens}" if self.hparams.freeze_embeds: freeze_embeds(self.model ) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder() ) assert_all_frozen(self.model.get_encoder() ) SCREAMING_SNAKE_CASE_ : str = get_git_info()["repo_sha"] SCREAMING_SNAKE_CASE_ : int = hparams.num_workers SCREAMING_SNAKE_CASE_ : Tuple = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , _A ): SCREAMING_SNAKE_CASE_ : int = self.tokenizer.lang_code_to_id[hparams.tgt_lang] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.decoder_start_token_id SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( SeqaSeqDataset if hasattr(self.tokenizer , "prepare_seq2seq_batch" ) else LegacySeqaSeqDataset ) SCREAMING_SNAKE_CASE_ : Optional[Any] = False SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.hparams.eval_max_gen_length else: SCREAMING_SNAKE_CASE_ : str = self.model.config.max_length SCREAMING_SNAKE_CASE_ : str = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = { k: self.tokenizer.batch_decode(v.tolist() ) if "mask" not in k else v.shape for k, v in batch.items() } save_json(_A , Path(self.output_dir ) / "text_batch.json" ) save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / "tok_batch.json" ) SCREAMING_SNAKE_CASE_ : List[str] = True return readable_batch def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" return self.model(_A , **_A ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer.batch_decode( _A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) return lmap(str.strip , _A ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer.pad_token_id SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = batch["input_ids"], batch["attention_mask"] SCREAMING_SNAKE_CASE_ : Tuple = batch["labels"] if isinstance(self.model , _A ): SCREAMING_SNAKE_CASE_ : Optional[int] = self.model._shift_right(_A ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = shift_tokens_right(_A , _A ) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero SCREAMING_SNAKE_CASE_ : Any = decoder_input_ids self.save_readable_batch(_A ) SCREAMING_SNAKE_CASE_ : List[Any] = self(_A , attention_mask=_A , decoder_input_ids=_A , use_cache=_A ) SCREAMING_SNAKE_CASE_ : List[Any] = outputs["logits"] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id SCREAMING_SNAKE_CASE_ : Any = nn.CrossEntropyLoss(ignore_index=_A ) assert lm_logits.shape[-1] == self.vocab_size SCREAMING_SNAKE_CASE_ : Any = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = nn.functional.log_softmax(_A , dim=-1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = label_smoothed_nll_loss( _A , _A , self.hparams.label_smoothing , ignore_index=_A ) return (loss,) @property def __lowerCamelCase ( self ): """simple docstring""" return self.tokenizer.pad_token_id def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self._step(_A ) SCREAMING_SNAKE_CASE_ : Optional[Any] = dict(zip(self.loss_names , _A ) ) # tokens per batch SCREAMING_SNAKE_CASE_ : Dict = batch["input_ids"].ne(self.pad ).sum() + batch["labels"].ne(self.pad ).sum() SCREAMING_SNAKE_CASE_ : List[str] = batch["input_ids"].shape[0] SCREAMING_SNAKE_CASE_ : Dict = batch["input_ids"].eq(self.pad ).sum() SCREAMING_SNAKE_CASE_ : List[Any] = batch["input_ids"].eq(self.pad ).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" return self._generative_step(_A ) def __lowerCamelCase ( self , lowercase__ , lowercase__="val" ): """simple docstring""" self.step_count += 1 SCREAMING_SNAKE_CASE_ : List[str] = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names} SCREAMING_SNAKE_CASE_ : int = losses["loss"] SCREAMING_SNAKE_CASE_ : Tuple = { k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ["gen_time", "gen_len"] } SCREAMING_SNAKE_CASE_ : Any = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) SCREAMING_SNAKE_CASE_ : int = torch.tensor(_A ).type_as(_A ) generative_metrics.update({k: v.item() for k, v in losses.items()} ) losses.update(_A ) SCREAMING_SNAKE_CASE_ : List[str] = {F"{prefix}_avg_{k}": x for k, x in losses.items()} SCREAMING_SNAKE_CASE_ : Dict = self.step_count self.metrics[prefix].append(_A ) # callback writes this to self.metrics_save_path SCREAMING_SNAKE_CASE_ : Union[str, Any] = flatten_list([x["preds"] for x in outputs] ) return { "log": all_metrics, "preds": preds, F"{prefix}_loss": loss, F"{prefix}_{self.val_metric}": metric_tensor, } def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" return calculate_rouge(_A , _A ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') SCREAMING_SNAKE_CASE_ : List[Any] = self.model.generate( batch["input_ids"] , attention_mask=batch["attention_mask"] , use_cache=_A , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) SCREAMING_SNAKE_CASE_ : int = (time.time() - ta) / batch["input_ids"].shape[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.ids_to_clean_text(_A ) SCREAMING_SNAKE_CASE_ : Tuple = self.ids_to_clean_text(batch["labels"] ) SCREAMING_SNAKE_CASE_ : str = self._step(_A ) SCREAMING_SNAKE_CASE_ : str = dict(zip(self.loss_names , _A ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.calc_generative_metrics(_A , _A ) SCREAMING_SNAKE_CASE_ : int = np.mean(lmap(_A , _A ) ) base_metrics.update(gen_time=_A , gen_len=_A , preds=_A , target=_A , **_A ) return base_metrics def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" return self._generative_step(_A ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.validation_epoch_end(_A , prefix="test" ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.n_obs[type_path] SCREAMING_SNAKE_CASE_ : int = self.target_lens[type_path] SCREAMING_SNAKE_CASE_ : Any = self.dataset_class( self.tokenizer , type_path=_A , n_obs=_A , max_target_length=_A , **self.dataset_kwargs , ) return dataset def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_dataset(_A ) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": SCREAMING_SNAKE_CASE_ : List[str] = dataset.make_sortish_sampler(_A , distributed=self.hparams.gpus > 1 ) return DataLoader( _A , batch_size=_A , collate_fn=dataset.collate_fn , shuffle=_A , num_workers=self.num_workers , sampler=_A , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": SCREAMING_SNAKE_CASE_ : Any = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 ) return DataLoader( _A , batch_sampler=_A , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( _A , batch_size=_A , collate_fn=dataset.collate_fn , shuffle=_A , num_workers=self.num_workers , sampler=_A , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.get_dataloader("train" , batch_size=self.hparams.train_batch_size , shuffle=_A ) return dataloader def __lowerCamelCase ( self ): """simple docstring""" return self.get_dataloader("val" , batch_size=self.hparams.eval_batch_size ) def __lowerCamelCase ( self ): """simple docstring""" return self.get_dataloader("test" , batch_size=self.hparams.eval_batch_size ) @staticmethod def __lowerCamelCase ( lowercase__ , lowercase__ ): """simple docstring""" BaseTransformer.add_model_specific_args(_A , _A ) add_generic_args(_A , _A ) parser.add_argument( "--max_source_length" , default=1024 , type=_A , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--max_target_length" , default=56 , type=_A , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--val_max_target_length" , default=142 , type=_A , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--test_max_target_length" , default=142 , type=_A , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument("--freeze_encoder" , action="store_true" ) parser.add_argument("--freeze_embeds" , action="store_true" ) parser.add_argument("--sortish_sampler" , action="store_true" , default=_A ) parser.add_argument("--overwrite_output_dir" , action="store_true" , default=_A ) parser.add_argument("--max_tokens_per_batch" , type=_A , default=_A ) parser.add_argument("--logger_name" , type=_A , choices=["default", "wandb", "wandb_shared"] , default="default" ) parser.add_argument("--n_train" , type=_A , default=-1 , required=_A , help="# examples. -1 means use all." ) parser.add_argument("--n_val" , type=_A , default=500 , required=_A , help="# examples. -1 means use all." ) parser.add_argument("--n_test" , type=_A , default=-1 , required=_A , help="# examples. -1 means use all." ) parser.add_argument( "--task" , type=_A , default="summarization" , required=_A , help="# examples. -1 means use all." ) parser.add_argument("--label_smoothing" , type=_A , default=0.0 , required=_A ) parser.add_argument("--src_lang" , type=_A , default="" , required=_A ) parser.add_argument("--tgt_lang" , type=_A , default="" , required=_A ) parser.add_argument("--eval_beams" , type=_A , default=_A , required=_A ) parser.add_argument( "--val_metric" , type=_A , default=_A , required=_A , choices=["bleu", "rouge2", "loss", None] ) parser.add_argument("--eval_max_gen_length" , type=_A , default=_A , help="never generate more than n tokens" ) parser.add_argument("--save_top_k" , type=_A , default=1 , required=_A , help="How many checkpoints to save" ) parser.add_argument( "--early_stopping_patience" , type=_A , default=-1 , required=_A , help=( "-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So" " val_check_interval will effect it." ) , ) return parser class SCREAMING_SNAKE_CASE__ ( __lowercase ): _A = "translation" _A = ["loss"] _A = ["bleu"] _A = "bleu" def __init__( self , lowercase__ , **lowercase__ ): """simple docstring""" super().__init__(_A , **_A ) SCREAMING_SNAKE_CASE_ : Any = hparams.src_lang SCREAMING_SNAKE_CASE_ : int = hparams.tgt_lang def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" return calculate_bleu(_A , _A ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int]=None ) -> Optional[int]: """simple docstring""" Path(args.output_dir ).mkdir(exist_ok=__snake_case ) check_output_dir(__snake_case , expected_items=3 ) if model is None: if "summarization" in args.task: SCREAMING_SNAKE_CASE_ : Optional[int] = SummarizationModule(__snake_case ) else: SCREAMING_SNAKE_CASE_ : Any = TranslationModule(__snake_case ) SCREAMING_SNAKE_CASE_ : Tuple = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith("/tmp" ) or str(args.output_dir ).startswith("/var" ) ): SCREAMING_SNAKE_CASE_ : List[Any] = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger SCREAMING_SNAKE_CASE_ : str = os.environ.get("WANDB_PROJECT" , __snake_case ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = WandbLogger(name=model.output_dir.name , project=__snake_case ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger SCREAMING_SNAKE_CASE_ : Optional[Any] = WandbLogger(name=model.output_dir.name , project=F"hf_{dataset}" ) if args.early_stopping_patience >= 0: SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_early_stopping_callback(model.val_metric , args.early_stopping_patience ) else: SCREAMING_SNAKE_CASE_ : Any = False SCREAMING_SNAKE_CASE_ : List[str] = args.val_metric == "loss" SCREAMING_SNAKE_CASE_ : Optional[Any] = generic_train( __snake_case , __snake_case , logging_callback=SeqaSeqLoggingCallback() , checkpoint_callback=get_checkpoint_callback( args.output_dir , model.val_metric , args.save_top_k , __snake_case ) , early_stopping_callback=__snake_case , logger=__snake_case , ) pickle_save(model.hparams , model.output_dir / "hparams.pkl" ) if not args.do_predict: return model SCREAMING_SNAKE_CASE_ : Dict = "" SCREAMING_SNAKE_CASE_ : Tuple = sorted(glob.glob(os.path.join(args.output_dir , "*.ckpt" ) , recursive=__snake_case ) ) if checkpoints: SCREAMING_SNAKE_CASE_ : Tuple = checkpoints[-1] SCREAMING_SNAKE_CASE_ : Optional[int] = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() snake_case_ = pl.Trainer.add_argparse_args(parser) snake_case_ = SummarizationModule.add_model_specific_args(parser, os.getcwd()) snake_case_ = parser.parse_args() main(args)
704
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : int = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __a ): _A = '''encoder-decoder''' _A = True def __init__( self , **lowercase__ ): """simple docstring""" super().__init__(**snake_case__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop("encoder" ) SCREAMING_SNAKE_CASE_ : Any = encoder_config.pop("model_type" ) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop("decoder" ) SCREAMING_SNAKE_CASE_ : Any = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.for_model(snake_case__ , **snake_case__ ) SCREAMING_SNAKE_CASE_ : Any = AutoConfig.for_model(snake_case__ , **snake_case__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = True @classmethod def __lowerCamelCase ( cls , lowercase__ , lowercase__ , **lowercase__ ): """simple docstring""" logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : List[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **snake_case__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.encoder.to_dict() SCREAMING_SNAKE_CASE_ : Tuple = self.decoder.to_dict() SCREAMING_SNAKE_CASE_ : Any = self.__class__.model_type return output
705
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[Any]: """simple docstring""" if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): SCREAMING_SNAKE_CASE_ : int = array[indexa], array[indexa] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int ) -> List[Any]: """simple docstring""" if length > 1: SCREAMING_SNAKE_CASE_ : Optional[Any] = int(length / 2 ) for i in range(lowerCAmelCase_ , low + middle ): comp_and_swap(lowerCAmelCase_ , lowerCAmelCase_ , i + middle , lowerCAmelCase_ ) bitonic_merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) bitonic_merge(lowerCAmelCase_ , low + middle , lowerCAmelCase_ , lowerCAmelCase_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]: """simple docstring""" if length > 1: SCREAMING_SNAKE_CASE_ : List[Any] = int(length / 2 ) bitonic_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 1 ) bitonic_sort(lowerCAmelCase_ , low + middle , lowerCAmelCase_ , 0 ) bitonic_merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item.strip()) for item in user_input.split(',')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('\nSorted array in ascending order is: ', end='') print(*unsorted, sep=', ') bitonic_merge(unsorted, 0, len(unsorted), 0) print('Sorted array in descending order is: ', end='') print(*unsorted, sep=', ')
706
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
0
'''simple docstring''' import os import sys import unittest snake_case_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path snake_case_ = os.path.join(git_repo_path, 'src', 'diffusers') class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = find_backend(" if not is_torch_available():" ) self.assertEqual(lowercase__ , "torch" ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") SCREAMING_SNAKE_CASE_ : Any = find_backend(" if not (is_torch_available() and is_transformers_available()):" ) self.assertEqual(lowercase__ , "torch_and_transformers" ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") SCREAMING_SNAKE_CASE_ : Optional[Any] = find_backend( " if not (is_torch_available() and is_transformers_available() and is_onnx_available()):" ) self.assertEqual(lowercase__ , "torch_and_transformers_and_onnx" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("torch" , lowercase__ ) self.assertIn("torch_and_transformers" , lowercase__ ) self.assertIn("flax_and_transformers" , lowercase__ ) self.assertIn("torch_and_transformers_and_onnx" , lowercase__ ) # Likewise, we can't assert on the exact content of a key self.assertIn("UNet2DModel" , objects["torch"] ) self.assertIn("FlaxUNet2DConditionModel" , objects["flax"] ) self.assertIn("StableDiffusionPipeline" , objects["torch_and_transformers"] ) self.assertIn("FlaxStableDiffusionPipeline" , objects["flax_and_transformers"] ) self.assertIn("LMSDiscreteScheduler" , objects["torch_and_scipy"] ) self.assertIn("OnnxStableDiffusionPipeline" , objects["torch_and_transformers_and_onnx"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = create_dummy_object("CONSTANT" , "'torch'" ) self.assertEqual(lowercase__ , "\nCONSTANT = None\n" ) SCREAMING_SNAKE_CASE_ : int = create_dummy_object("function" , "'torch'" ) self.assertEqual( lowercase__ , "\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n" ) SCREAMING_SNAKE_CASE_ : Optional[int] = "\nclass FakeClass(metaclass=DummyObject):\n _backends = 'torch'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, 'torch')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, 'torch')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, 'torch')\n" SCREAMING_SNAKE_CASE_ : Tuple = create_dummy_object("FakeClass" , "'torch'" ) self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = [\"torch\"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, [\"torch\"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, [\"torch\"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, [\"torch\"])\n" SCREAMING_SNAKE_CASE_ : Tuple = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]} ) self.assertEqual(dummy_files["torch"] , lowercase__ )
707
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ ): _A = ["image_processor", "tokenizer"] _A = "AutoImageProcessor" _A = "AutoTokenizer" def __init__( self , lowercase__ , lowercase__ ): """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : str = self.image_processor def __call__( self , lowercase__=None , lowercase__=None , lowercase__=None , **lowercase__ ): """simple docstring""" if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: SCREAMING_SNAKE_CASE_ : int = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None and images is not None: SCREAMING_SNAKE_CASE_ : int = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def __lowerCamelCase ( self ): """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
708
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
0
'''simple docstring''' import numpy as np def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] = 1E-1_2 , SCREAMING_SNAKE_CASE_ : List[Any] = 1_0_0 , ) -> str: """simple docstring""" assert np.shape(A_ )[0] == np.shape(A_ )[1] # Ensure proper dimensionality. assert np.shape(A_ )[0] == np.shape(A_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(A_ ) == np.iscomplexobj(A_ ) SCREAMING_SNAKE_CASE_ : Any = np.iscomplexobj(A_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(A_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 1E1_2 while not convergence: # Multiple matrix by the vector. SCREAMING_SNAKE_CASE_ : int = np.dot(A_ , A_ ) # Normalize the resulting output vector. SCREAMING_SNAKE_CASE_ : str = w / np.linalg.norm(A_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) SCREAMING_SNAKE_CASE_ : Any = vector.conj().T if is_complex else vector.T SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.dot(A_ , np.dot(A_ , A_ ) ) # Check convergence. SCREAMING_SNAKE_CASE_ : Tuple = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Union[str, Any] = lambda_ if is_complex: SCREAMING_SNAKE_CASE_ : List[str] = np.real(lambda_ ) return lambda_, vector def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) SCREAMING_SNAKE_CASE_ : str = np.array([4_1, 4, 2_0] ) SCREAMING_SNAKE_CASE_ : Tuple = real_input_matrix.astype(np.complexaaa ) SCREAMING_SNAKE_CASE_ : int = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T SCREAMING_SNAKE_CASE_ : Any = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": SCREAMING_SNAKE_CASE_ : int = real_input_matrix SCREAMING_SNAKE_CASE_ : Any = real_vector elif problem_type == "complex": SCREAMING_SNAKE_CASE_ : Optional[int] = complex_input_matrix SCREAMING_SNAKE_CASE_ : Union[str, Any] = complex_vector # Our implementation. SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = power_iteration(A_ , A_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = np.linalg.eigh(A_ ) # Last eigenvalue is the maximum one. SCREAMING_SNAKE_CASE_ : Dict = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. SCREAMING_SNAKE_CASE_ : Dict = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(A_ ) - np.abs(A_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
709
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ) )
68
0
'''simple docstring''' from __future__ import annotations snake_case_ = list[list[int]] # assigning initial values to the grid snake_case_ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution snake_case_ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Matrix | None: """simple docstring""" if location := find_empty_location(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : str = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 1_0 ): if is_safe(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Dict = digit if sudoku(SCREAMING_SNAKE_CASE_ ) is not None: return grid SCREAMING_SNAKE_CASE_ : List[Any] = 0 return None def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> None: """simple docstring""" for row in grid: for cell in row: print(SCREAMING_SNAKE_CASE_ , end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 2_0) print_solution(example_grid) print('\nExample grid solution:') snake_case_ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
710
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
0
'''simple docstring''' from __future__ import annotations import math def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True snake_case_ = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> list[int]: """simple docstring""" if not isinstance(__snake_case , __snake_case ): raise ValueError("n must be an integer" ) if n <= 0: raise ValueError("n must be >= 0" ) SCREAMING_SNAKE_CASE_ : str = [] for num in range(len(__snake_case ) ): SCREAMING_SNAKE_CASE_ : List[Any] = 0 while 2 * i * i <= odd_composites[num]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = odd_composites[num] - 2 * i * i if is_prime(__snake_case ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(__snake_case ) == n: return list_nums return [] def __lowerCamelCase ( ) -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F'''{solution() = }''')
711
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase_,unittest.TestCase ): _A = MobileBertTokenizer _A = MobileBertTokenizerFast _A = True _A = True _A = filter_non_english _A = "google/mobilebert-uncased" def __lowerCamelCase ( self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ : Optional[int] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE_ : str = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE_ : Any = """unwanted, running""" return input_text, output_text def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(lowerCamelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [9, 6, 7, 12, 10, 11] ) def __lowerCamelCase ( self ): """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE_ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[Any] = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # With lower casing SCREAMING_SNAKE_CASE_ : List[str] = self.get_tokenizer(do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_rust_tokenizer(do_lower_case=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[Any] = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Any = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = tokenizer.encode(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : int = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE_ : List[str] = {} for i, token in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ : List[str] = i SCREAMING_SNAKE_CASE_ : Union[str, Any] = WordpieceTokenizer(vocab=lowerCamelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def __lowerCamelCase ( self ): """simple docstring""" self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def __lowerCamelCase ( self ): """simple docstring""" self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def __lowerCamelCase ( self ): """simple docstring""" self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowerCamelCase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(lowerCamelCase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode("sequence builders" , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ , lowerCamelCase_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __lowerCamelCase ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Tuple = F"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_r.encode_plus( lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE_ : int = tokenizer_r.do_lower_case if hasattr(lowerCamelCase_ , "do_lower_case" ) else False SCREAMING_SNAKE_CASE_ : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE_ : Tuple = """""".join(lowerCamelCase_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : str = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = False SCREAMING_SNAKE_CASE_ : int = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Any = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : str = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Any = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE_ : List[str] = [ F"##{token}" if idx != 0 else token for idx, token in enumerate(lowerCamelCase_ ) ] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
712
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
0
'''simple docstring''' import os from collections.abc import Iterator def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str = "." ) -> Optional[Any]: """simple docstring""" for dir_path, dir_names, filenames in os.walk(A__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(A__ )[1] in (".py", ".ipynb"): yield os.path.join(A__ , A__ ).lstrip("./" ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" return F"{i * ' '}*" if i else "\n##" def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(A__ ) or old_parts[i] != new_part) and new_part: print(F"{md_prefix(A__ )} {new_part.replace('_' , ' ' ).title()}" ) return new_path def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str = "." ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = "" for filepath in sorted(good_file_paths(A__ ) ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = os.path.split(A__ ) if filepath != old_path: SCREAMING_SNAKE_CASE_ : Optional[Any] = print_path(A__ , A__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = (filepath.count(os.sep ) + 1) if filepath else 0 SCREAMING_SNAKE_CASE_ : Any = F"{filepath}/{filename}".replace(" " , "%20" ) SCREAMING_SNAKE_CASE_ : Any = os.path.splitext(filename.replace("_" , " " ).title() )[0] print(F"{md_prefix(A__ )} [{filename}]({url})" ) if __name__ == "__main__": print_directory_md('.')
713
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): _A = ["pixel_values"] def __init__( self , lowercase__ = True , lowercase__ = 1 / 255 , lowercase__ = True , lowercase__ = 8 , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : str = do_rescale SCREAMING_SNAKE_CASE_ : Optional[Any] = rescale_factor SCREAMING_SNAKE_CASE_ : Any = do_pad SCREAMING_SNAKE_CASE_ : Optional[Any] = pad_size def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ ): """simple docstring""" return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = get_image_size(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE_ : List[Any] = (old_width // size + 1) * size - old_width return pad(lowercase__ , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = ChannelDimension.FIRST , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : str = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE_ : Optional[int] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE_ : Tuple = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : Any = [to_numpy_array(lowercase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ : Any = [self.rescale(image=lowercase__ , scale=lowercase__ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE_ : Tuple = [self.pad(lowercase__ , size=lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [to_channel_dimension_format(lowercase__ , lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : Optional[Any] = {"pixel_values": images} return BatchFeature(data=lowercase__ , tensor_type=lowercase__ )
714
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpr" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=0 , lowercase__="absolute" , lowercase__ = 0 , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase_ , **lowercase_ ) SCREAMING_SNAKE_CASE_ : Any = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : str = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : int = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Tuple = type_vocab_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : int = layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = projection_dim SCREAMING_SNAKE_CASE_ : Dict = position_embedding_type
715
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
0
'''simple docstring''' import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py snake_case_ = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) snake_case_ = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = SavedModel() SCREAMING_SNAKE_CASE_ : Dict = [] with open(os.path.join(snake_case__ , "utils" , "tf_ops" , "onnx.json" ) ) as f: SCREAMING_SNAKE_CASE_ : int = json.load(snake_case__ )["opsets"] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(snake_case__ )] ) with open(snake_case__ , "rb" ) as f: saved_model.ParseFromString(f.read() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want SCREAMING_SNAKE_CASE_ : List[str] = sorted(snake_case__ ) SCREAMING_SNAKE_CASE_ : List[Any] = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(snake_case__ ) if strict and len(snake_case__ ) > 0: raise Exception(F"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops ) elif len(snake_case__ ) > 0: print(F"Found the following incompatible ops for the opset {opset}:" ) print(*snake_case__ , sep="\n" ) else: print(F"The saved model {saved_model_path} can properly be converted with ONNX." ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=1_2, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) snake_case_ = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
716
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import os import sys snake_case_ = 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, ) snake_case_ = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Dict , **SCREAMING_SNAKE_CASE_ : Any ) -> int: """simple docstring""" return AutoConfig.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: """simple docstring""" return AutoTokenizer.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoModel.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: """simple docstring""" return AutoModel.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : List[str] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int: """simple docstring""" return AutoModelForCausalLM.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Optional[int] , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: """simple docstring""" return AutoModelForMaskedLM.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : List[str] , **SCREAMING_SNAKE_CASE_ : Any ) -> Any: """simple docstring""" return AutoModelForSequenceClassification.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : int , **SCREAMING_SNAKE_CASE_ : str ) -> Tuple: """simple docstring""" return AutoModelForQuestionAnswering.from_pretrained(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
717
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' from __future__ import annotations import pandas as pd def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = [0] * no_of_processes SCREAMING_SNAKE_CASE_ : Optional[Any] = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Dict = burst_time[i] SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : Any = 9_9_9_9_9_9_9_9_9 SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = False # Process until all processes are completed while complete != no_of_processes: for j in range(SCREAMING_SNAKE_CASE_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: SCREAMING_SNAKE_CASE_ : str = remaining_time[j] SCREAMING_SNAKE_CASE_ : Dict = j SCREAMING_SNAKE_CASE_ : str = True if not check: increment_time += 1 continue remaining_time[short] -= 1 SCREAMING_SNAKE_CASE_ : Dict = remaining_time[short] if minm == 0: SCREAMING_SNAKE_CASE_ : Dict = 9_9_9_9_9_9_9_9_9 if remaining_time[short] == 0: complete += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = False # Find finish time of current process SCREAMING_SNAKE_CASE_ : Optional[int] = increment_time + 1 # Calculate waiting time SCREAMING_SNAKE_CASE_ : Any = finish_time - arrival_time[short] SCREAMING_SNAKE_CASE_ : Optional[int] = finar - burst_time[short] if waiting_time[short] < 0: SCREAMING_SNAKE_CASE_ : str = 0 # Increment time increment_time += 1 return waiting_time def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [0] * no_of_processes for i in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Optional[int] = burst_time[i] + waiting_time[i] return turn_around_time def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 0 SCREAMING_SNAKE_CASE_ : str = 0 for i in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = total_waiting_time + waiting_time[i] SCREAMING_SNAKE_CASE_ : List[Any] = total_turn_around_time + turn_around_time[i] print(F"Average waiting time = {total_waiting_time / no_of_processes:.5f}" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('Enter how many process you want to analyze') snake_case_ = int(input()) snake_case_ = [0] * no_of_processes snake_case_ = [0] * no_of_processes snake_case_ = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('Enter the arrival time and burst time for process:--' + str(i + 1)) snake_case_ = map(int, input().split()) snake_case_ = calculate_waitingtime(arrival_time, burst_time, no_of_processes) snake_case_ = burst_time snake_case_ = no_of_processes snake_case_ = waiting_time snake_case_ = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) snake_case_ = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ 'Process', 'BurstTime', 'ArrivalTime', 'WaitingTime', 'TurnAroundTime', ], ) # Printing the dataFrame pd.set_option('display.max_rows', fcfs.shape[0] + 1) print(fcfs)
718
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
0
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = FileLock(str(tmpdir / "foo.lock" ) ) SCREAMING_SNAKE_CASE_ : List[Any] = FileLock(str(tmpdir / "foo.lock" ) ) SCREAMING_SNAKE_CASE_ : int = 0.01 with locka.acquire(): with pytest.raises(__a ): SCREAMING_SNAKE_CASE_ : Optional[int] = time.time() locka.acquire(__a ) assert time.time() - _start > timeout def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = "a" * 1_0_0_0 + ".lock" SCREAMING_SNAKE_CASE_ : Optional[int] = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(__a ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 SCREAMING_SNAKE_CASE_ : int = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(__a ): locka.acquire(0 )
719
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
0
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING snake_case_ = logging.get_logger(__name__) @add_end_docstrings(_snake_case ) class SCREAMING_SNAKE_CASE__ ( _snake_case ): def __init__( self , *lowercase__ , **lowercase__ ): """simple docstring""" super().__init__(*snake_case_ , **snake_case_ ) requires_backends(self , "decord" ) self.check_model_type(snake_case_ ) def __lowerCamelCase ( self , lowercase__=None , lowercase__=None , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = {} if frame_sampling_rate is not None: SCREAMING_SNAKE_CASE_ : Dict = frame_sampling_rate if num_frames is not None: SCREAMING_SNAKE_CASE_ : List[str] = num_frames SCREAMING_SNAKE_CASE_ : Dict = {} if top_k is not None: SCREAMING_SNAKE_CASE_ : Any = top_k return preprocess_params, {}, postprocess_params def __call__( self , lowercase__ , **lowercase__ ): """simple docstring""" return super().__call__(snake_case_ , **snake_case_ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None , lowercase__=1 ): """simple docstring""" if num_frames is None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.model.config.num_frames if video.startswith("http://" ) or video.startswith("https://" ): SCREAMING_SNAKE_CASE_ : str = BytesIO(requests.get(snake_case_ ).content ) SCREAMING_SNAKE_CASE_ : Optional[int] = VideoReader(snake_case_ ) videoreader.seek(0 ) SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = num_frames * frame_sampling_rate - 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.linspace(snake_case_ , snake_case_ , num=snake_case_ , dtype=np.intaa ) SCREAMING_SNAKE_CASE_ : Optional[int] = videoreader.get_batch(snake_case_ ).asnumpy() SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(snake_case_ ) SCREAMING_SNAKE_CASE_ : str = self.image_processor(snake_case_ , return_tensors=self.framework ) return model_inputs def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.model(**snake_case_ ) return model_outputs def __lowerCamelCase ( self , lowercase__ , lowercase__=5 ): """simple docstring""" if top_k > self.model.config.num_labels: SCREAMING_SNAKE_CASE_ : Tuple = self.model.config.num_labels if self.framework == "pt": SCREAMING_SNAKE_CASE_ : List[str] = model_outputs.logits.softmax(-1 )[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = probs.topk(snake_case_ ) else: raise ValueError(F"Unsupported framework: {self.framework}" ) SCREAMING_SNAKE_CASE_ : List[Any] = scores.tolist() SCREAMING_SNAKE_CASE_ : Any = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case_ , snake_case_ )]
720
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
0
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = question_encoder SCREAMING_SNAKE_CASE_ : Tuple = generator SCREAMING_SNAKE_CASE_ : Any = self.question_encoder def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if os.path.isfile(UpperCAmelCase__ ): raise ValueError(F"Provided path ({save_directory}) should be a directory, not a file" ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Any = os.path.join(UpperCAmelCase__ , "question_encoder_tokenizer" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(UpperCAmelCase__ , "generator_tokenizer" ) self.question_encoder.save_pretrained(UpperCAmelCase__ ) self.generator.save_pretrained(UpperCAmelCase__ ) @classmethod def __lowerCamelCase ( cls , lowercase__ , **lowercase__ ): """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop("config" , UpperCAmelCase__ ) if config is None: SCREAMING_SNAKE_CASE_ : Dict = RagConfig.from_pretrained(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Tuple = AutoTokenizer.from_pretrained( UpperCAmelCase__ , config=config.question_encoder , subfolder="question_encoder_tokenizer" ) SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained( UpperCAmelCase__ , config=config.generator , subfolder="generator_tokenizer" ) return cls(question_encoder=UpperCAmelCase__ , generator=UpperCAmelCase__ ) def __call__( self , *lowercase__ , **lowercase__ ): """simple docstring""" return self.current_tokenizer(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" return self.generator.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" return self.generator.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.question_encoder def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.generator def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = "longest" , lowercase__ = None , lowercase__ = True , **lowercase__ , ): """simple docstring""" warnings.warn( "`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the " "regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` " "context manager to prepare your targets. See the documentation of your specific tokenizer for more " "details" , UpperCAmelCase__ , ) if max_length is None: SCREAMING_SNAKE_CASE_ : int = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE_ : List[str] = self( UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: SCREAMING_SNAKE_CASE_ : Any = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE_ : int = self( text_target=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ , ) SCREAMING_SNAKE_CASE_ : Dict = labels['''input_ids'''] return model_inputs
721
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
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 PreTrainedTokenizer from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = '▁' snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'google/reformer-crime-and-punishment': ( 'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model' ) } } snake_case_ = { 'google/reformer-crime-and-punishment': 5_2_4_2_8_8, } class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__="</s>" , lowercase__="<unk>" , lowercase__=[] , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.sp_model.get_piece_size() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : int = {} SCREAMING_SNAKE_CASE_ : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.piece_to_id(_lowerCamelCase ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if index < self.sp_model.get_piece_size(): SCREAMING_SNAKE_CASE_ : List[str] = self.sp_model.IdToPiece(_lowerCamelCase ) return token def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] SCREAMING_SNAKE_CASE_ : List[Any] = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE_ : List[str] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(_lowerCamelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join( _lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
700
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
0
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> Optional[Any]: """simple docstring""" return round(float(moles / volume ) * nfactor ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> str: """simple docstring""" return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> Optional[int]: """simple docstring""" return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> Tuple: """simple docstring""" return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
701
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available snake_case_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer snake_case_ = ['bert-base-uncased', 'bert-base-cased'] snake_case_ = 'hf-internal-testing/tiny-bert-tf-only' if is_tf_available(): class SCREAMING_SNAKE_CASE__ ( tf.keras.Model ): def __init__( self , lowercase__ ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer SCREAMING_SNAKE_CASE_ : List[str] = AutoConfig.from_pretrained(lowercase_ ) SCREAMING_SNAKE_CASE_ : List[str] = TFAutoModel.from_config(lowercase_ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer(lowercase_ ) SCREAMING_SNAKE_CASE_ : str = self.bert(**lowercase_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ : Dict = [ BertTokenizer.from_pretrained(lowercase_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false SCREAMING_SNAKE_CASE_ : Tuple = [TFBertTokenizer.from_pretrained(lowercase_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(lowercase_ , use_fast_bert_tokenizer=lowercase_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) SCREAMING_SNAKE_CASE_ : Dict = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] SCREAMING_SNAKE_CASE_ : str = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __lowerCamelCase ( self ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): SCREAMING_SNAKE_CASE_ : Any = tokenizer(lowercase_ , return_tensors="tf" , padding="longest" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf_tokenizer(lowercase_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def __lowerCamelCase ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf_tokenizer(self.paired_sentences ) SCREAMING_SNAKE_CASE_ : str = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def __lowerCamelCase ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ : int = tf.function(lowercase_ ) for test_inputs in (self.test_sentences, self.paired_sentences): SCREAMING_SNAKE_CASE_ : Optional[int] = tf.constant(lowercase_ ) SCREAMING_SNAKE_CASE_ : Tuple = compiled_tokenizer(lowercase_ ) SCREAMING_SNAKE_CASE_ : Any = tf_tokenizer(lowercase_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __lowerCamelCase ( self ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ : List[Any] = ModelToSave(tokenizer=lowercase_ ) SCREAMING_SNAKE_CASE_ : Any = tf.convert_to_tensor(self.test_sentences ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE_ : Optional[Any] = Path(lowercase_ ) / "saved.model" model.save(lowercase_ ) SCREAMING_SNAKE_CASE_ : Tuple = tf.keras.models.load_model(lowercase_ ) SCREAMING_SNAKE_CASE_ : str = loaded_model(lowercase_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
703
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
0
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : _A = 42 _A = 42 class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[] for _ in range(A_ )] SCREAMING_SNAKE_CASE_ : Tuple = size def __getitem__( self , lowercase__ ): """simple docstring""" return iter(self._graph[vertex] ) @property def __lowerCamelCase ( self ): """simple docstring""" return self._size def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(A_ , A_ ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = deque([start_vertex] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [None] * self.size SCREAMING_SNAKE_CASE_ : List[Any] = 0 while queue: SCREAMING_SNAKE_CASE_ : Dict = queue.popleft() SCREAMING_SNAKE_CASE_ : Any = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: SCREAMING_SNAKE_CASE_ : List[Any] = current_distance + edge.weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = distances[edge.destination_vertex] if ( isinstance(A_ , A_ ) and new_distance >= dest_vertex_distance ): continue SCREAMING_SNAKE_CASE_ : Optional[int] = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
704
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ : List[str] = { 'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RemBertConfig', 'RemBertOnnxConfig'] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : int = ['RemBertTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = ['RemBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Any = [ 'REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RemBertForCausalLM', 'RemBertForMaskedLM', 'RemBertForMultipleChoice', 'RemBertForQuestionAnswering', 'RemBertForSequenceClassification', 'RemBertForTokenClassification', 'RemBertLayer', 'RemBertModel', 'RemBertPreTrainedModel', 'load_tf_weights_in_rembert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[Any] = [ 'TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRemBertForCausalLM', 'TFRemBertForMaskedLM', 'TFRemBertForMultipleChoice', 'TFRemBertForQuestionAnswering', 'TFRemBertForSequenceClassification', 'TFRemBertForTokenClassification', 'TFRemBertLayer', 'TFRemBertModel', 'TFRemBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys snake_case_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow snake_case_ = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ "text-classification", "language-modeling", "summarization", "token-classification", "question-answering", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = argparse.ArgumentParser() parser.add_argument("-f" ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() return args.f def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str="eval" ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join(_SCREAMING_SNAKE_CASE , F"{split}_results.json" ) if os.path.exists(_SCREAMING_SNAKE_CASE ): with open(_SCREAMING_SNAKE_CASE , "r" ) as f: return json.load(_SCREAMING_SNAKE_CASE ) raise ValueError(F"can\'t find {path}" ) snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : List[Any] = F"\n run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --eval_steps=2\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_flax_glue.main() SCREAMING_SNAKE_CASE_ : List[str] = get_results(__UpperCamelCase ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : Any = F"\n run_clm_flax.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --block_size 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_clm_flax.main() SCREAMING_SNAKE_CASE_ : int = get_results(__UpperCamelCase ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : str = F"\n run_summarization.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --test_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=8\n --do_train\n --do_eval\n --do_predict\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --predict_with_generate\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_summarization_flax.main() SCREAMING_SNAKE_CASE_ : Optional[Any] = get_results(__UpperCamelCase , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : Tuple = F"\n run_mlm.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --logging_steps 2 --eval_steps 2\n --do_train\n --do_eval\n --num_train_epochs=1\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_mlm_flax.main() SCREAMING_SNAKE_CASE_ : Dict = get_results(__UpperCamelCase ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : Tuple = F"\n run_t5_mlm_flax.py\n --model_name_or_path t5-small\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE_ : Optional[Any] = get_results(__UpperCamelCase ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : Any = F"\n run_flax_ner.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --do_train\n --do_eval\n --warmup_steps=2\n --learning_rate=2e-4\n --logging_steps 2 --eval_steps 2\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_flax_ner.main() SCREAMING_SNAKE_CASE_ : Tuple = get_results(__UpperCamelCase ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE_ : Optional[Any] = F"\n run_qa.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=2\n --do_train\n --do_eval\n --logging_steps 2 --eval_steps 2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n ".split() with patch.object(__UpperCamelCase , "argv" , __UpperCamelCase ): run_qa.main() SCREAMING_SNAKE_CASE_ : Tuple = get_results(__UpperCamelCase ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
706
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
0
'''simple docstring''' import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( A_,unittest.TestCase ): _A = OpenAIGPTTokenizer _A = OpenAIGPTTokenizerFast _A = True _A = False def __lowerCamelCase ( self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ : Optional[Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE_ : Any = dict(zip(lowercase__ , range(len(lowercase__ ) ) ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(lowercase__ ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(lowercase__ ) ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return "lower newer", "lower newer" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE_ : int = """lower""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE_ : int = tokenizer.tokenize(lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE_ : Dict = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) , lowercase__ ) def __lowerCamelCase ( self , lowercase__=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE_ : Optional[int] = self.rust_tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) # Simple input SCREAMING_SNAKE_CASE_ : Tuple = """This is a simple input""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE_ : List[str] = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE_ : Any = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(lowercase__ , tokenizer_r.encode , lowercase__ , max_length=lowercase__ , padding="max_length" ) # Simple input self.assertRaises(lowercase__ , tokenizer_r.encode_plus , lowercase__ , max_length=lowercase__ , padding="max_length" ) # Simple input self.assertRaises( lowercase__ , tokenizer_r.batch_encode_plus , lowercase__ , max_length=lowercase__ , padding="max_length" , ) # Pair input self.assertRaises(lowercase__ , tokenizer_r.encode , lowercase__ , max_length=lowercase__ , padding="max_length" ) # Pair input self.assertRaises(lowercase__ , tokenizer_r.encode_plus , lowercase__ , max_length=lowercase__ , padding="max_length" ) # Pair input self.assertRaises( lowercase__ , tokenizer_r.batch_encode_plus , lowercase__ , max_length=lowercase__ , padding="max_length" , ) def __lowerCamelCase ( self ): """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class SCREAMING_SNAKE_CASE__ ( A_ ): pass
707
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
708
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin snake_case_ = random.Random() if is_torch_available(): import torch def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple=1.0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None , SCREAMING_SNAKE_CASE_ : str=None ) -> Tuple: """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = global_rng SCREAMING_SNAKE_CASE_ : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=400 , lowercase__=2000 , lowercase__=1 , lowercase__=0.0 , lowercase__=1_6000 , lowercase__=True , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = parent SCREAMING_SNAKE_CASE_ : List[str] = batch_size SCREAMING_SNAKE_CASE_ : Optional[int] = min_seq_length SCREAMING_SNAKE_CASE_ : Optional[Any] = max_seq_length SCREAMING_SNAKE_CASE_ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE_ : List[str] = feature_size SCREAMING_SNAKE_CASE_ : int = padding_value SCREAMING_SNAKE_CASE_ : Optional[int] = sampling_rate SCREAMING_SNAKE_CASE_ : Optional[int] = return_attention_mask SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_normalize def __lowerCamelCase ( self ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False ): """simple docstring""" def _flatten(lowercase__ ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE_ : Any = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE_ : Any = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE_ : Optional[int] = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE__ ( a__,unittest.TestCase ): _A = ASTFeatureExtractor def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = ASTFeatureExtractionTester(self ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE_ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE_ : Tuple = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE_ : List[Any] = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values SCREAMING_SNAKE_CASE_ : Tuple = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = feat_extract(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors="np" ).input_values SCREAMING_SNAKE_CASE_ : Any = feat_extract(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE_ : List[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE_ : str = np.asarray(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : str = feat_extract(lowerCamelCase_ , return_tensors="np" ).input_values SCREAMING_SNAKE_CASE_ : Optional[int] = feat_extract(lowerCamelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) @require_torch def __lowerCamelCase ( self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE_ : List[Any] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE_ : Tuple = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE_ : int = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE_ : int = ds.sort("id" ).select(range(lowerCamelCase_ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on SCREAMING_SNAKE_CASE_ : Tuple = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE_ : int = ASTFeatureExtractor() SCREAMING_SNAKE_CASE_ : List[str] = feature_extractor(lowerCamelCase_ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , lowerCamelCase_ , atol=1e-4 ) )
709
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ) )
68
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) snake_case_ = torch.device('cpu') def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE_ : Any = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple ) -> List[Any]: """simple docstring""" if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = dct.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = val def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [] for k in state_dict.keys(): SCREAMING_SNAKE_CASE_ : str = k if ".pwconv" in k: SCREAMING_SNAKE_CASE_ : List[Any] = k_new.replace(".pwconv" , ".point_wise_conv" ) if ".dwconv" in k: SCREAMING_SNAKE_CASE_ : str = k_new.replace(".dwconv" , ".depth_wise_conv" ) if ".Proj." in k: SCREAMING_SNAKE_CASE_ : Union[str, Any] = k_new.replace(".Proj." , ".proj." ) if "patch_embed" in k_new: SCREAMING_SNAKE_CASE_ : int = k_new.replace("patch_embed" , "swiftformer.patch_embed.patch_embedding" ) if "network" in k_new: SCREAMING_SNAKE_CASE_ : List[str] = k_new.split("." ) if ls[2].isdigit(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = "swiftformer.encoder.network." + ls[1] + ".blocks." + ls[2] + "." + ".".join(ls[3:] ) else: SCREAMING_SNAKE_CASE_ : str = k_new.replace("network" , "swiftformer.encoder.network" ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1_0_0_0 SCREAMING_SNAKE_CASE_ : Optional[Any] = "huggingface/label-files" SCREAMING_SNAKE_CASE_ : Optional[int] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE_ : List[Any] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE_ : int = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : Optional[int] = idalabel SCREAMING_SNAKE_CASE_ : str = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": SCREAMING_SNAKE_CASE_ : List[str] = [3, 3, 6, 4] SCREAMING_SNAKE_CASE_ : List[Any] = [4_8, 5_6, 1_1_2, 2_2_0] elif swiftformer_name == "swiftformer_s": SCREAMING_SNAKE_CASE_ : Any = [3, 3, 9, 6] SCREAMING_SNAKE_CASE_ : int = [4_8, 6_4, 1_6_8, 2_2_4] elif swiftformer_name == "swiftformer_l1": SCREAMING_SNAKE_CASE_ : Dict = [4, 3, 1_0, 5] SCREAMING_SNAKE_CASE_ : Any = [4_8, 9_6, 1_9_2, 3_8_4] elif swiftformer_name == "swiftformer_l3": SCREAMING_SNAKE_CASE_ : int = [4, 4, 1_2, 6] SCREAMING_SNAKE_CASE_ : str = [6_4, 1_2_8, 3_2_0, 5_1_2] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith("https" ): SCREAMING_SNAKE_CASE_ : int = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_ , map_location="cpu" , check_hash=SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ : int = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = checkpoint SCREAMING_SNAKE_CASE_ : List[str] = create_rename_keys(SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load HuggingFace model SCREAMING_SNAKE_CASE_ : List[Any] = SwiftFormerForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() hf_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # prepare test inputs SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[int] = ViTImageProcessor.from_pretrained("preprocessor_config" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="pt" ) # compare outputs from both models SCREAMING_SNAKE_CASE_ : List[str] = get_expected_output(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = hf_model(inputs["pixel_values"] ).logits assert hf_logits.shape == torch.Size([1, 1_0_0_0] ) assert torch.allclose(hf_logits[0, 0:5] , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(F"Saving model {swiftformer_name} to {pytorch_dump_folder_path}" ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') snake_case_ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
710
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ) -> list: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) SCREAMING_SNAKE_CASE_ : int = result + left + right return input_list def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> list: """simple docstring""" if len(__lowerCAmelCase ) <= 1: return input_list SCREAMING_SNAKE_CASE_ : Any = list(__lowerCAmelCase ) # iteration for two-way merging SCREAMING_SNAKE_CASE_ : Tuple = 2 while p <= len(__lowerCAmelCase ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : int = i SCREAMING_SNAKE_CASE_ : Tuple = i + p - 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = (low + high + 1) // 2 SCREAMING_SNAKE_CASE_ : Dict = merge(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # final merge of last two parts if p * 2 >= len(__lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] = i SCREAMING_SNAKE_CASE_ : Union[str, Any] = merge(__lowerCAmelCase , 0 , __lowerCAmelCase , len(__lowerCAmelCase ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() if user_input == "": snake_case_ = [] else: snake_case_ = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
711
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import copy import re class SCREAMING_SNAKE_CASE__ : _A = "hp" _A = {} _A = None @classmethod def __lowerCamelCase ( cls , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = prefix SCREAMING_SNAKE_CASE_ : List[str] = defaults cls.build_naming_info() @staticmethod def __lowerCamelCase ( lowercase__ , lowercase__ ): """simple docstring""" if len(_UpperCAmelCase ) == 0: return "" SCREAMING_SNAKE_CASE_ : Optional[int] = None if any(char.isdigit() for char in word ): raise Exception(F"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_UpperCAmelCase ) + 1 ): SCREAMING_SNAKE_CASE_ : str = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE_ : Tuple = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = '''''' while integer != 0: SCREAMING_SNAKE_CASE_ : Union[str, Any] = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s SCREAMING_SNAKE_CASE_ : Optional[int] = 0 while True: SCREAMING_SNAKE_CASE_ : List[str] = word + '''#''' + int_to_alphabetic(_UpperCAmelCase ) if sword in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE_ : Optional[Any] = sword break SCREAMING_SNAKE_CASE_ : List[str] = short_word SCREAMING_SNAKE_CASE_ : Dict = word return short_word @staticmethod def __lowerCamelCase ( lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = param_name.split("_" ) SCREAMING_SNAKE_CASE_ : str = [TrialShortNamer.shortname_for_word(_UpperCAmelCase , _UpperCAmelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name SCREAMING_SNAKE_CASE_ : Dict = ['''''', '''_'''] for separator in separators: SCREAMING_SNAKE_CASE_ : Union[str, Any] = separator.join(_UpperCAmelCase ) if shortname not in info["reverse_short_param"]: SCREAMING_SNAKE_CASE_ : List[str] = shortname SCREAMING_SNAKE_CASE_ : Union[str, Any] = param_name return shortname return param_name @staticmethod def __lowerCamelCase ( lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = TrialShortNamer.shortname_for_key(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = short_name SCREAMING_SNAKE_CASE_ : Optional[Any] = param_name @classmethod def __lowerCamelCase ( cls ): """simple docstring""" if cls.NAMING_INFO is not None: return SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''short_word''': {}, '''reverse_short_word''': {}, '''short_param''': {}, '''reverse_short_param''': {}, } SCREAMING_SNAKE_CASE_ : List[str] = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = info @classmethod def __lowerCamelCase ( cls , lowercase__ ): """simple docstring""" cls.build_naming_info() assert cls.PREFIX is not None SCREAMING_SNAKE_CASE_ : str = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = cls.NAMING_INFO['''short_param'''][k] if isinstance(_UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_ : str = 1 if v else 0 SCREAMING_SNAKE_CASE_ : Tuple = '''''' if isinstance(_UpperCAmelCase , (int, float) ) else '''-''' SCREAMING_SNAKE_CASE_ : Dict = F"{key}{sep}{v}" name.append(_UpperCAmelCase ) return "_".join(_UpperCAmelCase ) @classmethod def __lowerCamelCase ( cls , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = repr[len(cls.PREFIX ) + 1 :] if repr == "": SCREAMING_SNAKE_CASE_ : Tuple = [] else: SCREAMING_SNAKE_CASE_ : str = repr.split("_" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = {} for value in values: if "-" in value: SCREAMING_SNAKE_CASE_ : List[Any] = value.split("-" ) else: SCREAMING_SNAKE_CASE_ : int = re.sub("[0-9.]" , "" , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = float(re.sub("[^0-9.]" , "" , _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_ : Dict = cls.NAMING_INFO['''reverse_short_param'''][p_k] SCREAMING_SNAKE_CASE_ : Union[str, Any] = p_v for k in cls.DEFAULTS: if k not in parameters: SCREAMING_SNAKE_CASE_ : Optional[int] = cls.DEFAULTS[k] return parameters
712
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
0
'''simple docstring''' import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _a,unittest.TestCase ): _A = PriorTransformer _A = "hidden_states" @property def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = 4 SCREAMING_SNAKE_CASE_ : Dict = 8 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 7 SCREAMING_SNAKE_CASE_ : Any = floats_tensor((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = floats_tensor((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(_A ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def __lowerCamelCase ( self , lowercase__=0 ): """simple docstring""" torch.manual_seed(_A ) SCREAMING_SNAKE_CASE_ : Any = 4 SCREAMING_SNAKE_CASE_ : Dict = 8 SCREAMING_SNAKE_CASE_ : int = 7 SCREAMING_SNAKE_CASE_ : Dict = torch.randn((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.randn((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_A ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def __lowerCamelCase ( self ): """simple docstring""" return (4, 8) @property def __lowerCamelCase ( self ): """simple docstring""" return (4, 8) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = { "num_attention_heads": 2, "attention_head_dim": 4, "num_layers": 2, "embedding_dim": 8, "num_embeddings": 7, "additional_embeddings": 4, } SCREAMING_SNAKE_CASE_ : Optional[Any] = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = PriorTransformer.from_pretrained( "hf-internal-testing/prior-dummy" , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(_A ) SCREAMING_SNAKE_CASE_ : Any = model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_class(**_A ) SCREAMING_SNAKE_CASE_ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : List[str] = ["hidden_states", "timestep"] self.assertListEqual(arg_names[:2] , _A ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" ) SCREAMING_SNAKE_CASE_ : Optional[int] = model.to(_A ) if hasattr(_A , "set_default_attn_processor" ): model.set_default_attn_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_seed_input() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(**_A )[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = output[0, :5].flatten().cpu() print(_A ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([-1.3436, -0.2870, 0.7538, 0.4368, -0.0239] ) self.assertTrue(torch_all_close(_A , _A , rtol=1e-2 ) ) @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self , lowercase__=1 , lowercase__=768 , lowercase__=77 , lowercase__=0 ): """simple docstring""" torch.manual_seed(_A ) SCREAMING_SNAKE_CASE_ : int = batch_size SCREAMING_SNAKE_CASE_ : Optional[int] = embedding_dim SCREAMING_SNAKE_CASE_ : Any = num_embeddings SCREAMING_SNAKE_CASE_ : Tuple = torch.randn((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : Any = torch.randn((batch_size, embedding_dim) ).to(_A ) SCREAMING_SNAKE_CASE_ : str = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_A ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def __lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.5861, 0.1283, -0.0931, 0.0882, 0.4476, 0.1329, -0.0498, 0.0640]], [37, [-0.4913, 0.0110, -0.0483, 0.0541, 0.4954, -0.0170, 0.0354, 0.1651]], # fmt: on ] ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior" , subfolder="prior" ) model.to(_A ) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_seed_input(seed=_A ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(**_A )[0] assert list(sample.shape ) == [1, 768] SCREAMING_SNAKE_CASE_ : Dict = sample[0, :8].flatten().cpu() print(_A ) SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor(_A ) assert torch_all_close(_A , _A , atol=1e-3 )
713
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} # See all BART models at https://huggingface.co/models?filter=bart snake_case_ = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, } snake_case_ = { 'facebook/bart-base': 1_0_2_4, 'facebook/bart-large': 1_0_2_4, 'facebook/bart-large-mnli': 1_0_2_4, 'facebook/bart-large-cnn': 1_0_2_4, 'facebook/bart-large-xsum': 1_0_2_4, 'yjernite/bart_eli5': 1_0_2_4, } @lru_cache() def __lowerCamelCase ( ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = bs[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(UpperCAmelCase__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE_ : Any = [chr(UpperCAmelCase__ ) for n in cs] return dict(zip(UpperCAmelCase__ , UpperCAmelCase__ ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = set() SCREAMING_SNAKE_CASE_ : str = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = char return pairs class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__ , lowercase__="replace" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="</s>" , lowercase__="<s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__=False , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else bos_token SCREAMING_SNAKE_CASE_ : Optional[Any] = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else eos_token SCREAMING_SNAKE_CASE_ : Any = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else sep_token SCREAMING_SNAKE_CASE_ : Optional[int] = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else cls_token SCREAMING_SNAKE_CASE_ : Any = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else unk_token SCREAMING_SNAKE_CASE_ : str = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_ : List[str] = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else mask_token super().__init__( errors=__UpperCamelCase , bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , cls_token=__UpperCamelCase , pad_token=__UpperCamelCase , mask_token=__UpperCamelCase , add_prefix_space=__UpperCamelCase , **__UpperCamelCase , ) with open(__UpperCamelCase , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE_ : List[Any] = json.load(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : Any = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE_ : List[Any] = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE_ : int = bytes_to_unicode() SCREAMING_SNAKE_CASE_ : Tuple = {v: k for k, v in self.byte_encoder.items()} with open(__UpperCamelCase , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE_ : Union[str, Any] = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE_ : int = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE_ : Optional[Any] = dict(zip(__UpperCamelCase , range(len(__UpperCamelCase ) ) ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE_ : str = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def __lowerCamelCase ( self ): """simple docstring""" return len(self.encoder ) def __lowerCamelCase ( self ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = get_pairs(__UpperCamelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE_ : Tuple = min(__UpperCamelCase , key=lambda lowercase__ : self.bpe_ranks.get(__UpperCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = bigram SCREAMING_SNAKE_CASE_ : Tuple = [] SCREAMING_SNAKE_CASE_ : Dict = 0 while i < len(__UpperCamelCase ): try: SCREAMING_SNAKE_CASE_ : Optional[Any] = word.index(__UpperCamelCase , __UpperCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE_ : Tuple = j if word[i] == first and i < len(__UpperCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = tuple(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_word if len(__UpperCamelCase ) == 1: break else: SCREAMING_SNAKE_CASE_ : List[Any] = get_pairs(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = " ".join(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : List[Any] = word return word def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for token in re.findall(self.pat , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ : Tuple = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__UpperCamelCase ).split(" " ) ) return bpe_tokens def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.encoder.get(__UpperCamelCase , self.encoder.get(self.unk_token ) ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.decoder.get(__UpperCamelCase ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = "".join(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(__UpperCamelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : List[str] = os.path.join( __UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( __UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(__UpperCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__UpperCamelCase , ensure_ascii=__UpperCamelCase ) + "\n" ) SCREAMING_SNAKE_CASE_ : int = 0 with open(__UpperCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowercase__ : kv[1] ): if index != token_index: logger.warning( F"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE_ : int = token_index writer.write(" ".join(__UpperCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE_ : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCamelCase , token_ids_a=__UpperCamelCase , already_has_special_tokens=__UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCamelCase )) + [1] return [1] + ([0] * len(__UpperCamelCase )) + [1, 1] + ([0] * len(__UpperCamelCase )) + [1] def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCamelCase ( self , lowercase__ , lowercase__=False , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__UpperCamelCase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE_ : Optional[int] = " " + text return (text, kwargs)
714
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.txt'} snake_case_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } snake_case_ = { 'YituTech/conv-bert-base': 5_1_2, 'YituTech/conv-bert-medium-small': 5_1_2, 'YituTech/conv-bert-small': 5_1_2, } snake_case_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_INIT_CONFIGURATION _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ConvBertTokenizer def __init__( self , lowercase__=None , lowercase__=None , lowercase__=True , lowercase__="[UNK]" , lowercase__="[SEP]" , lowercase__="[PAD]" , lowercase__="[CLS]" , lowercase__="[MASK]" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__( lowercase__ , tokenizer_file=lowercase__ , do_lower_case=lowercase__ , unk_token=lowercase__ , sep_token=lowercase__ , pad_token=lowercase__ , cls_token=lowercase__ , mask_token=lowercase__ , tokenize_chinese_chars=lowercase__ , strip_accents=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowercase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowercase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowercase__ ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE_ : Optional[Any] = getattr(lowercase__ , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : str = do_lower_case SCREAMING_SNAKE_CASE_ : List[str] = strip_accents SCREAMING_SNAKE_CASE_ : Tuple = tokenize_chinese_chars SCREAMING_SNAKE_CASE_ : Optional[int] = normalizer_class(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = do_lower_case def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [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 __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [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 __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ )
715
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
0
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]: """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), F"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: SCREAMING_SNAKE_CASE_ : Optional[Any] = F"The input value of [n={number}] has to be > 0" raise ValueError(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ : Any = sylvester(number - 1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = num - 1 SCREAMING_SNAKE_CASE_ : Dict = num return lower * upper + 1 if __name__ == "__main__": print(F'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
716
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]: """simple docstring""" if collection == []: return [] # get some information about the collection SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = max(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = min(SCREAMING_SNAKE_CASE_ ) # create the counting array SCREAMING_SNAKE_CASE_ : Optional[Any] = coll_max + 1 - coll_min SCREAMING_SNAKE_CASE_ : List[Any] = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = counting_arr[i] + counting_arr[i - 1] # create the output collection SCREAMING_SNAKE_CASE_ : Optional[Any] = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE_ : int = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> Optional[Any]: """simple docstring""" return "".join([chr(SCREAMING_SNAKE_CASE_ ) for i in counting_sort([ord(SCREAMING_SNAKE_CASE_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('thisisthestring') == "eghhiiinrsssttt" snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(counting_sort(unsorted))
717
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch snake_case_ = random.Random() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Tuple=1.0 , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , SCREAMING_SNAKE_CASE_ : List[Any]=None ) -> Optional[int]: """simple docstring""" if rng is None: SCREAMING_SNAKE_CASE_ : Tuple = global_rng SCREAMING_SNAKE_CASE_ : List[str] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=400 , lowercase__=2000 , lowercase__=10 , lowercase__=160 , lowercase__=8 , lowercase__=0.0 , lowercase__=4000 , lowercase__=False , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = parent SCREAMING_SNAKE_CASE_ : Dict = batch_size SCREAMING_SNAKE_CASE_ : List[Any] = min_seq_length SCREAMING_SNAKE_CASE_ : Tuple = max_seq_length SCREAMING_SNAKE_CASE_ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE_ : str = padding_value SCREAMING_SNAKE_CASE_ : Union[str, Any] = sampling_rate SCREAMING_SNAKE_CASE_ : List[str] = return_attention_mask SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = feature_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = chunk_length SCREAMING_SNAKE_CASE_ : List[Any] = hop_length def __lowerCamelCase ( self ): """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False ): """simple docstring""" def _flatten(lowercase__ ): return list(itertools.chain(*lowercase__ ) ) if equal_length: SCREAMING_SNAKE_CASE_ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE_ : str = [np.asarray(lowercase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_,unittest.TestCase ): _A = WhisperFeatureExtractor if is_speech_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = WhisperFeatureExtractionTester(self ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : List[str] = feat_extract_first.save_pretrained(lowercase__ )[0] check_json_file_has_correct_format(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = self.feature_extraction_class.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE_ : Union[str, Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE_ : int = feat_extract_first.mel_filters SCREAMING_SNAKE_CASE_ : Any = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowercase__ , lowercase__ ) ) self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(lowercase__ , "feat_extract.json" ) feat_extract_first.to_json_file(lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.feature_extraction_class.from_json_file(lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE_ : Union[str, Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE_ : List[str] = feat_extract_first.mel_filters SCREAMING_SNAKE_CASE_ : Optional[int] = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowercase__ , lowercase__ ) ) self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE_ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE_ : Tuple = [np.asarray(lowercase__ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor(lowercase__ , padding="max_length" , return_tensors="np" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input SCREAMING_SNAKE_CASE_ : List[str] = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_features SCREAMING_SNAKE_CASE_ : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_features self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = feature_extractor(lowercase__ , return_tensors="np" ).input_features SCREAMING_SNAKE_CASE_ : List[Any] = feature_extractor(lowercase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(lowercase__ , lowercase__ ): self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE_ : Optional[int] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = feature_extractor(lowercase__ , return_tensors="np" ).input_features SCREAMING_SNAKE_CASE_ : List[Any] = feature_extractor(lowercase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(lowercase__ , lowercase__ ): self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # Test truncation required SCREAMING_SNAKE_CASE_ : str = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] SCREAMING_SNAKE_CASE_ : str = [np.asarray(lowercase__ ) for speech_input in speech_inputs] SCREAMING_SNAKE_CASE_ : str = [x[: feature_extractor.n_samples] for x in speech_inputs] SCREAMING_SNAKE_CASE_ : int = [np.asarray(lowercase__ ) for speech_input in speech_inputs_truncated] SCREAMING_SNAKE_CASE_ : Dict = feature_extractor(lowercase__ , return_tensors="np" ).input_features SCREAMING_SNAKE_CASE_ : List[str] = feature_extractor(lowercase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(lowercase__ , lowercase__ ): self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) def __lowerCamelCase ( self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE_ : Dict = np.random.rand(100 , 32 ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE_ : Tuple = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) SCREAMING_SNAKE_CASE_ : Any = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE_ : List[str] = ds.sort("id" ).select(range(lowercase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on SCREAMING_SNAKE_CASE_ : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE_ : Dict = WhisperFeatureExtractor() SCREAMING_SNAKE_CASE_ : Optional[int] = feature_extractor(lowercase__ , return_tensors="pt" ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , lowercase__ , atol=1e-4 ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE_ : Dict = self._load_datasamples(1 )[0] SCREAMING_SNAKE_CASE_ : str = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue SCREAMING_SNAKE_CASE_ : Optional[int] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=lowercase__ )[0] self.assertTrue(np.all(np.mean(lowercase__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowercase__ ) - 1 ) < 1e-3 ) )
718
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
0
'''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__ ( lowercase_,lowercase_,lowercase_ ): @register_to_config def __init__( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ = False , ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ : int = nn.Embedding(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : str = nn.Embedding(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : Tuple = nn.Dropout(p=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = TaConfig( vocab_size=lowercase__ , d_model=lowercase__ , num_heads=lowercase__ , d_kv=lowercase__ , d_ff=lowercase__ , dropout_rate=lowercase__ , feed_forward_proj=lowercase__ , is_decoder=lowercase__ , is_encoder_decoder=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = nn.ModuleList() for lyr_num in range(lowercase__ ): SCREAMING_SNAKE_CASE_ : int = TaBlock(lowercase__ ) self.encoders.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TaLayerNorm(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.Dropout(p=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.token_embedder(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = encoder_input_tokens.shape[1] SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.arange(lowercase__ , device=encoder_input_tokens.device ) x += self.position_encoding(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = self.dropout_pre(lowercase__ ) # inverted the attention mask SCREAMING_SNAKE_CASE_ : str = encoder_input_tokens.size() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_extended_attention_mask(lowercase__ , lowercase__ ) for lyr in self.encoders: SCREAMING_SNAKE_CASE_ : List[str] = lyr(lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE_ : Any = self.layer_norm(lowercase__ ) return self.dropout_post(lowercase__ ), encoder_inputs_mask
719
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) snake_case_ = { 'configuration_wav2vec2': ['WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Wav2Vec2Config'], 'feature_extraction_wav2vec2': ['Wav2Vec2FeatureExtractor'], 'processing_wav2vec2': ['Wav2Vec2Processor'], 'tokenization_wav2vec2': ['Wav2Vec2CTCTokenizer', 'Wav2Vec2Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Wav2Vec2ForAudioFrameClassification', 'Wav2Vec2ForCTC', 'Wav2Vec2ForMaskedLM', 'Wav2Vec2ForPreTraining', 'Wav2Vec2ForSequenceClassification', 'Wav2Vec2ForXVector', 'Wav2Vec2Model', 'Wav2Vec2PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWav2Vec2ForCTC', 'TFWav2Vec2Model', 'TFWav2Vec2PreTrainedModel', 'TFWav2Vec2ForSequenceClassification', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FlaxWav2Vec2ForCTC', 'FlaxWav2Vec2ForPreTraining', 'FlaxWav2Vec2Model', 'FlaxWav2Vec2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
720
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
0
'''simple docstring''' from statistics import mean import numpy as np def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 # Number of processes finished SCREAMING_SNAKE_CASE_ : List[Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. SCREAMING_SNAKE_CASE_ : List[Any] = [0] * no_of_process # List to include calculation results SCREAMING_SNAKE_CASE_ : int = [0] * no_of_process # Sort by arrival time. SCREAMING_SNAKE_CASE_ : List[Any] = [burst_time[i] for i in np.argsort(SCREAMING_SNAKE_CASE_ )] SCREAMING_SNAKE_CASE_ : str = [process_name[i] for i in np.argsort(SCREAMING_SNAKE_CASE_ )] arrival_time.sort() while no_of_process > finished_process_count: SCREAMING_SNAKE_CASE_ : List[Any] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: SCREAMING_SNAKE_CASE_ : List[Any] = arrival_time[i] SCREAMING_SNAKE_CASE_ : List[Any] = 0 # Index showing the location of the process being performed SCREAMING_SNAKE_CASE_ : str = 0 # Saves the current response ratio. SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 for i in range(0 , SCREAMING_SNAKE_CASE_ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: SCREAMING_SNAKE_CASE_ : Optional[Any] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: SCREAMING_SNAKE_CASE_ : str = temp SCREAMING_SNAKE_CASE_ : str = i # Calculate the turn around time SCREAMING_SNAKE_CASE_ : Optional[Any] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. SCREAMING_SNAKE_CASE_ : Dict = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [0] * no_of_process for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Dict = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": snake_case_ = 5 snake_case_ = ['A', 'B', 'C', 'D', 'E'] snake_case_ = [1, 2, 3, 4, 5] snake_case_ = [1, 2, 3, 4, 5] snake_case_ = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) snake_case_ = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('Process name \tArrival time \tBurst time \tTurn around time \tWaiting time') for i in range(0, no_of_process): print( F'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' F'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(F'''average waiting time : {mean(waiting_time):.5f}''') print(F'''average turn around time : {mean(turn_around_time):.5f}''')
721
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
0
'''simple docstring''' from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP snake_case_ = logging.get_logger(__name__) # pylint: disable=invalid-name snake_case_ = '\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n >>> pipe.to("cuda")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save("cat.png")\n ```\n' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str=8 ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): """simple docstring""" super().__init__() self.register_modules( text_encoder=lowercase__ , tokenizer=lowercase__ , unet=lowercase__ , scheduler=lowercase__ , movq=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" if latents is None: SCREAMING_SNAKE_CASE_ : Tuple = randn_tensor(lowercase__ , generator=lowercase__ , device=lowercase__ , dtype=lowercase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) SCREAMING_SNAKE_CASE_ : List[str] = latents.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = latents * scheduler.init_noise_sigma return latents def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = len(lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else 1 # get prompt text embeddings SCREAMING_SNAKE_CASE_ : Any = self.tokenizer( lowercase__ , padding="max_length" , truncation=lowercase__ , max_length=77 , return_attention_mask=lowercase__ , add_special_tokens=lowercase__ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = text_inputs.input_ids SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase__ , padding="longest" , return_tensors="pt" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) 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}" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text_input_ids.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = text_inputs.attention_mask.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_encoder( input_ids=lowercase__ , attention_mask=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = prompt_embeds.repeat_interleave(lowercase__ , dim=0 ) SCREAMING_SNAKE_CASE_ : Tuple = text_encoder_hidden_states.repeat_interleave(lowercase__ , dim=0 ) SCREAMING_SNAKE_CASE_ : Optional[int] = text_mask.repeat_interleave(lowercase__ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ : List[str] if negative_prompt is None: SCREAMING_SNAKE_CASE_ : int = [""] * batch_size elif type(lowercase__ ) is not type(lowercase__ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(lowercase__ )} !=" F" {type(lowercase__ )}." ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = [negative_prompt] elif batch_size != len(lowercase__ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(lowercase__ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = negative_prompt SCREAMING_SNAKE_CASE_ : str = self.tokenizer( lowercase__ , padding="max_length" , max_length=77 , truncation=lowercase__ , return_attention_mask=lowercase__ , add_special_tokens=lowercase__ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE_ : List[Any] = uncond_input.input_ids.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = uncond_input.attention_mask.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.text_encoder( input_ids=lowercase__ , attention_mask=lowercase__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE_ : List[Any] = negative_prompt_embeds.shape[1] SCREAMING_SNAKE_CASE_ : Dict = negative_prompt_embeds.repeat(1 , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = uncond_text_encoder_hidden_states.shape[1] SCREAMING_SNAKE_CASE_ : Tuple = uncond_text_encoder_hidden_states.repeat(1 , lowercase__ , 1 ) SCREAMING_SNAKE_CASE_ : str = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , lowercase__ , -1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = uncond_text_mask.repeat_interleave(lowercase__ , dim=0 ) # done duplicates # 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 SCREAMING_SNAKE_CASE_ : str = torch.cat([negative_prompt_embeds, prompt_embeds] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) SCREAMING_SNAKE_CASE_ : Dict = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __lowerCamelCase ( self , lowercase__=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.device(F"cuda:{gpu_id}" ) SCREAMING_SNAKE_CASE_ : Optional[int] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowercase__ , lowercase__ ) def __lowerCamelCase ( self , lowercase__=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) SCREAMING_SNAKE_CASE_ : List[str] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=lowercase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: SCREAMING_SNAKE_CASE_ : List[Any] = cpu_offload_with_hook(lowercase__ , lowercase__ , prev_module_hook=lowercase__ ) if self.safety_checker is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = cpu_offload_with_hook(self.safety_checker , lowercase__ , prev_module_hook=lowercase__ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE_ : int = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): """simple docstring""" if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowercase__ , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(lowercase__ ) def __call__( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ = None , lowercase__ = 512 , lowercase__ = 512 , lowercase__ = 100 , lowercase__ = 4.0 , lowercase__ = 1 , lowercase__ = None , lowercase__ = None , lowercase__ = "pil" , lowercase__ = True , ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = 1 elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = len(lowercase__ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowercase__ )}" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self._execution_device SCREAMING_SNAKE_CASE_ : Dict = batch_size * num_images_per_prompt SCREAMING_SNAKE_CASE_ : Optional[int] = guidance_scale > 1.0 SCREAMING_SNAKE_CASE_ : str = self._encode_prompt( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : int = torch.cat(lowercase__ , dim=0 ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = torch.cat(lowercase__ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_embeds.repeat_interleave(lowercase__ , dim=0 ) SCREAMING_SNAKE_CASE_ : List[str] = negative_image_embeds.repeat_interleave(lowercase__ , dim=0 ) SCREAMING_SNAKE_CASE_ : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=lowercase__ ) self.scheduler.set_timesteps(lowercase__ , device=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler.timesteps SCREAMING_SNAKE_CASE_ : Tuple = self.unet.config.in_channels SCREAMING_SNAKE_CASE_ : Dict = get_new_h_w(lowercase__ , lowercase__ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , lowercase__ , lowercase__ , lowercase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowercase__ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE_ : List[Any] = {"text_embeds": prompt_embeds, "image_embeds": image_embeds} SCREAMING_SNAKE_CASE_ : Dict = self.unet( sample=lowercase__ , timestep=lowercase__ , encoder_hidden_states=lowercase__ , added_cond_kwargs=lowercase__ , return_dict=lowercase__ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ : List[Any] = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE_ : int = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE_ : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE_ : Tuple = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_ : str = self.scheduler.step( lowercase__ , lowercase__ , lowercase__ , generator=lowercase__ , ).prev_sample # post-processing SCREAMING_SNAKE_CASE_ : Optional[Any] = self.movq.decode(lowercase__ , force_not_quantize=lowercase__ )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE_ : int = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ : Dict = self.numpy_to_pil(lowercase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase__ )
700
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) snake_case_ = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
701
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "vit_mae" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=224 , lowercase__=16 , lowercase__=3 , lowercase__=True , lowercase__=16 , lowercase__=512 , lowercase__=8 , lowercase__=2048 , lowercase__=0.75 , lowercase__=False , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = image_size SCREAMING_SNAKE_CASE_ : Dict = patch_size SCREAMING_SNAKE_CASE_ : List[str] = num_channels SCREAMING_SNAKE_CASE_ : Optional[int] = qkv_bias SCREAMING_SNAKE_CASE_ : str = decoder_num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = decoder_hidden_size SCREAMING_SNAKE_CASE_ : Any = decoder_num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = decoder_intermediate_size SCREAMING_SNAKE_CASE_ : int = mask_ratio SCREAMING_SNAKE_CASE_ : Any = norm_pix_loss
702
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
0
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int ) -> List[Any]: """simple docstring""" if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(SCREAMING_SNAKE_CASE_ , n - 1 , SCREAMING_SNAKE_CASE_ ) * a) % mod else: SCREAMING_SNAKE_CASE_ : List[str] = binary_exponentiation(SCREAMING_SNAKE_CASE_ , n / 2 , SCREAMING_SNAKE_CASE_ ) return (b * b) % mod # a prime number snake_case_ = 7_0_1 snake_case_ = 1_0_0_0_0_0_0_0_0_0 snake_case_ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
703
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
0
'''simple docstring''' import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE_ : Dict = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = -1 SCREAMING_SNAKE_CASE_ : int = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.generate(lowercase__ , max_new_tokens=10 , do_sample=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_ : Any = TextStreamer(lowercase__ ) model.generate(lowercase__ , max_new_tokens=10 , do_sample=lowercase__ , streamer=lowercase__ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE_ : Tuple = cs.out[:-1] self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = -1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.generate(lowercase__ , max_new_tokens=10 , do_sample=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.decode(greedy_ids[0] ) SCREAMING_SNAKE_CASE_ : Dict = TextIteratorStreamer(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE_ : int = Thread(target=model.generate , kwargs=lowercase__ ) thread.start() SCREAMING_SNAKE_CASE_ : Tuple = "" for new_text in streamer: streamer_text += new_text self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = -1 SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model.generate(lowercase__ , max_new_tokens=10 , do_sample=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_ : List[str] = TextStreamer(lowercase__ , skip_prompt=lowercase__ ) model.generate(lowercase__ , max_new_tokens=10 , do_sample=lowercase__ , streamer=lowercase__ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE_ : List[str] = cs.out[:-1] self.assertEqual(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained("distilgpt2" ) SCREAMING_SNAKE_CASE_ : List[str] = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = -1 SCREAMING_SNAKE_CASE_ : Tuple = torch.ones((1, 5) , device=lowercase__ ).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_ : List[str] = TextStreamer(lowercase__ , skip_special_tokens=lowercase__ ) model.generate(lowercase__ , max_new_tokens=1 , do_sample=lowercase__ , streamer=lowercase__ ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE_ : Optional[int] = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE_ : Dict = tokenizer(lowercase__ , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = -1 SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = TextIteratorStreamer(lowercase__ , timeout=0.001 ) SCREAMING_SNAKE_CASE_ : Dict = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE_ : Optional[Any] = Thread(target=model.generate , kwargs=lowercase__ ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Dict = "" for new_text in streamer: streamer_text += new_text
704
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
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, is_vision_available, ) snake_case_ : Tuple = { 'configuration_clip': [ 'CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPConfig', 'CLIPOnnxConfig', 'CLIPTextConfig', 'CLIPVisionConfig', ], 'processing_clip': ['CLIPProcessor'], 'tokenization_clip': ['CLIPTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[Any] = ['CLIPTokenizerFast'] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = ['CLIPFeatureExtractor'] snake_case_ : Optional[int] = ['CLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ 'CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPModel', 'CLIPPreTrainedModel', 'CLIPTextModel', 'CLIPTextModelWithProjection', 'CLIPVisionModel', 'CLIPVisionModelWithProjection', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Union[str, Any] = [ 'TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCLIPModel', 'TFCLIPPreTrainedModel', 'TFCLIPTextModel', 'TFCLIPVisionModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = [ 'FlaxCLIPModel', 'FlaxCLIPPreTrainedModel', 'FlaxCLIPTextModel', 'FlaxCLIPTextPreTrainedModel', 'FlaxCLIPVisionModel', 'FlaxCLIPVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys snake_case_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
0
'''simple docstring''' from itertools import permutations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : Any = [7, 1_1, 1_3, 1_7] for i, test in enumerate(SCREAMING_SNAKE_CASE_ ): if (num[i + 4] * 1_0_0 + num[i + 5] * 1_0 + num[i + 6]) % test != 0: return False return True def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int = 1_0 ) -> int: """simple docstring""" return sum( int("".join(map(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) for num in permutations(range(SCREAMING_SNAKE_CASE_ ) ) if is_substring_divisible(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
706
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
0
'''simple docstring''' import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments snake_case_ = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = field( default=0.0,metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) _A = field(default=_UpperCAmelCase,metadata={"help": "Whether to SortishSamler or not."} ) _A = field( default=_UpperCAmelCase,metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) _A = field(default=_UpperCAmelCase,metadata={"help": "whether to use adafactor"} ) _A = field( default=_UpperCAmelCase,metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) _A = field( default=_UpperCAmelCase,metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) _A = field(default=_UpperCAmelCase,metadata={"help": "Dropout probability. Goes into model.config."} ) _A = field( default=_UpperCAmelCase,metadata={"help": "Attention dropout probability. Goes into model.config."} ) _A = field( default="linear",metadata={"help": f"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"},)
707
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
0
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = IFImgaImgSuperResolutionPipeline _A = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"} _A = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"} ) _A = PipelineTesterMixin.required_optional_params - {"latents"} def __lowerCamelCase ( self ): """simple docstring""" return self._get_superresolution_dummy_components() def __lowerCamelCase ( self , lowercase__ , lowercase__=0 ): """simple docstring""" if str(lowercase__ ).startswith("mps" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Any = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 16, 16) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __lowerCamelCase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def __lowerCamelCase ( self ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def __lowerCamelCase ( self ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __lowerCamelCase ( self ): """simple docstring""" self._test_save_load_local() def __lowerCamelCase ( self ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
708
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
0
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _A = field(default="question-answering-extractive",metadata={"include_in_asdict_even_if_is_default": True} ) _A = Features({"question": Value("string" ), "context": Value("string" )} ) _A = Features( { "answers": Sequence( { "text": Value("string" ), "answer_start": Value("int32" ), } ) } ) _A = "question" _A = "context" _A = "answers" @property def __lowerCamelCase ( self ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
709
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ) )
68
0
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): snake_case_ = 'pt' elif is_tf_available(): snake_case_ = 'tf' else: snake_case_ = 'jax' class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ByTaTokenizer _A = False def __lowerCamelCase ( self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ : int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowerCamelCase ( self ): """simple docstring""" return ByTaTokenizer.from_pretrained("google/byt5-small" ) def __lowerCamelCase ( self , **lowercase__ ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=False , lowercase__=20 , lowercase__=5 ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(len(lowercase__ ) ): try: SCREAMING_SNAKE_CASE_ : Dict = tokenizer.decode([i] , clean_up_tokenization_spaces=lowercase__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) SCREAMING_SNAKE_CASE_ : str = list(filter(lambda lowercase__ : re.match(r"^[ a-zA-Z]+$" , t[1] ) , lowercase__ ) ) SCREAMING_SNAKE_CASE_ : int = list(filter(lambda lowercase__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=lowercase__ ) , lowercase__ ) ) if max_length is not None and len(lowercase__ ) > max_length: SCREAMING_SNAKE_CASE_ : int = toks[:max_length] if min_length is not None and len(lowercase__ ) < min_length and len(lowercase__ ) > 0: while len(lowercase__ ) < min_length: SCREAMING_SNAKE_CASE_ : Dict = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE_ : Tuple = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.decode(lowercase__ , clean_up_tokenization_spaces=lowercase__ ) if " " not in output_txt and len(lowercase__ ) > 1: SCREAMING_SNAKE_CASE_ : List[str] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=lowercase__ ) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=lowercase__ ) ) if with_prefix_space: SCREAMING_SNAKE_CASE_ : List[str] = " " + output_txt SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) return output_txt, output_ids def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : str = tokenizer(["hi</s>", "I went to the gym</s>", "</s>"] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer(["hi", "I went to the gym", ""] ) self.assertListEqual(batch_with_eos_added["input_ids"] , batch_without_eos_added["input_ids"] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : int = "Unicode €." SCREAMING_SNAKE_CASE_ : int = tokenizer(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded["input_ids"] , lowercase__ ) # decoding SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.decode(lowercase__ ) self.assertEqual(lowercase__ , "Unicode €.</s>" ) SCREAMING_SNAKE_CASE_ : int = tokenizer("e è é ê ë" ) SCREAMING_SNAKE_CASE_ : List[Any] = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded["input_ids"] , lowercase__ ) # decoding SCREAMING_SNAKE_CASE_ : Dict = tokenizer.decode(lowercase__ ) self.assertEqual(lowercase__ , "e è é ê ë</s>" ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) ) , "e è é ê ë</s>" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : int = ["A long paragraph for summarization.", "Another paragraph for summarization."] # fmt: off SCREAMING_SNAKE_CASE_ : List[Any] = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on SCREAMING_SNAKE_CASE_ : str = tokenizer(lowercase__ , padding=lowercase__ , return_tensors=lowercase__ ) self.assertIsInstance(lowercase__ , lowercase__ ) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE_ : Tuple = list(batch.input_ids.numpy()[0] ) else: SCREAMING_SNAKE_CASE_ : Tuple = list(batch.input_ids.tolist()[0] ) self.assertListEqual(lowercase__ , lowercase__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : int = ["A long paragraph for summarization.", "Another paragraph for summarization."] SCREAMING_SNAKE_CASE_ : str = tokenizer(lowercase__ , padding=lowercase__ , return_tensors=lowercase__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn("input_ids" , lowercase__ ) self.assertIn("attention_mask" , lowercase__ ) self.assertNotIn("decoder_input_ids" , lowercase__ ) self.assertNotIn("decoder_attention_mask" , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : Any = [ "Summary of the text.", "Another summary.", ] SCREAMING_SNAKE_CASE_ : Dict = tokenizer( text_target=lowercase__ , max_length=32 , padding="max_length" , truncation=lowercase__ , return_tensors=lowercase__ ) self.assertEqual(32 , targets["input_ids"].shape[1] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.ta_base_tokenizer SCREAMING_SNAKE_CASE_ : Tuple = ["A long paragraph for summarization. </s>"] SCREAMING_SNAKE_CASE_ : List[str] = ["Summary of the text. </s>"] # fmt: off SCREAMING_SNAKE_CASE_ : List[str] = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] SCREAMING_SNAKE_CASE_ : str = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer(lowercase__ , text_target=lowercase__ ) self.assertEqual(lowercase__ , batch["input_ids"][0] ) self.assertEqual(lowercase__ , batch["labels"][0] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test SCREAMING_SNAKE_CASE_ : str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : int = " He is very happy, UNwant\u00E9d,running" SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) tokenizer.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tokenizer.__class__.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = after_tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ ) shutil.rmtree(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : int = " He is very happy, UNwant\u00E9d,running" tokenizer.add_tokens(["bim", "bambam"] ) SCREAMING_SNAKE_CASE_ : Any = tokenizer.additional_special_tokens additional_special_tokens.append("new_additional_special_token" ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) tokenizer.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = tokenizer.__class__.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = after_tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ ) self.assertIn("new_additional_special_token" , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.__class__.from_pretrained(lowercase__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowercase__ ) with open(os.path.join(lowercase__ , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: SCREAMING_SNAKE_CASE_ : str = json.load(lowercase__ ) with open(os.path.join(lowercase__ , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: SCREAMING_SNAKE_CASE_ : Optional[int] = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = [F"<extra_id_{i}>" for i in range(125 )] SCREAMING_SNAKE_CASE_ : List[str] = added_tokens_extra_ids + [ "an_additional_special_token" ] SCREAMING_SNAKE_CASE_ : Any = added_tokens_extra_ids + [ "an_additional_special_token" ] with open(os.path.join(lowercase__ , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase__ , lowercase__ ) with open(os.path.join(lowercase__ , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase__ , lowercase__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE_ : Dict = tokenizer_class.from_pretrained( lowercase__ , ) self.assertIn( "an_additional_special_token" , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ["an_additional_special_token"] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE_ : Optional[int] = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token" , lstrip=lowercase__ )] SCREAMING_SNAKE_CASE_ : int = tokenizer_class.from_pretrained( lowercase__ , additional_special_tokens=lowercase__ , ) self.assertIn("a_new_additional_special_token" , tokenizer.additional_special_tokens ) self.assertEqual( ["a_new_additional_special_token"] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"] ) ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer_class.from_pretrained(lowercase__ ) self.assertTrue(tokenizer.decode([255] ) == "" ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.get_tokenizers(fast=lowercase__ , do_lower_case=lowercase__ ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE_ : List[Any] = ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"] SCREAMING_SNAKE_CASE_ : Any = tokenizer.convert_tokens_to_string(lowercase__ ) self.assertIsInstance(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : int = tokenizer.convert_ids_to_tokens( lowercase__ , skip_special_tokens=lowercase__ ) for attr in attributes_list: setattr(lowercase__ , attr + "_id" , lowercase__ ) self.assertEqual(getattr(lowercase__ , lowercase__ ) , lowercase__ ) self.assertEqual(getattr(lowercase__ , attr + "_id" ) , lowercase__ ) setattr(lowercase__ , attr + "_id" , lowercase__ ) self.assertEqual(getattr(lowercase__ , lowercase__ ) , lowercase__ ) self.assertEqual(getattr(lowercase__ , attr + "_id" ) , lowercase__ ) setattr(lowercase__ , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(lowercase__ , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(lowercase__ , "additional_special_tokens_ids" ) , [] ) setattr(lowercase__ , "additional_special_tokens_ids" , [token_id_to_test_setters] ) self.assertListEqual(getattr(lowercase__ , "additional_special_tokens" ) , [token_to_test_setters] ) self.assertListEqual(getattr(lowercase__ , "additional_special_tokens_ids" ) , [token_id_to_test_setters] )
710
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class SCREAMING_SNAKE_CASE__ : def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return None class SCREAMING_SNAKE_CASE__ : def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return None class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _A = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def __lowerCamelCase ( self ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase__ , "tf" , 12 , **lowercase__ ) @require_torch @slow def __lowerCamelCase ( self ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase__ , "pt" , 12 , **lowercase__ ) @require_torch @slow def __lowerCamelCase ( self ): """simple docstring""" from transformers import BertModel SCREAMING_SNAKE_CASE_ : Tuple = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(lowercase__ ) ) vocab_file.flush() SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: SCREAMING_SNAKE_CASE_ : Dict = BertModel(BertConfig(vocab_size=len(lowercase__ ) ) ) model.save_pretrained(lowercase__ ) self._test_export(lowercase__ , "pt" , 12 , lowercase__ ) @require_tf @slow def __lowerCamelCase ( self ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE_ : Optional[int] = self._test_export(lowercase__ , "tf" , 12 , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = quantize(Path(lowercase__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase__ ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def __lowerCamelCase ( self ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: SCREAMING_SNAKE_CASE_ : List[Any] = self._test_export(lowercase__ , "pt" , 12 , **lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = quantize(lowercase__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase__ ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" try: # Compute path with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE_ : Union[str, Any] = Path(lowercase__ ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , **lowercase__ ) return path except Exception as e: self.fail(lowercase__ ) @require_torch @require_tokenizers @slow def __lowerCamelCase ( self ): """simple docstring""" from transformers import BertModel SCREAMING_SNAKE_CASE_ : List[Any] = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE_ : Any = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(lowercase__ , lowercase__ , "pt" ) @require_tf @require_tokenizers @slow def __lowerCamelCase ( self ): """simple docstring""" from transformers import TFBertModel SCREAMING_SNAKE_CASE_ : Optional[Any] = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) SCREAMING_SNAKE_CASE_ : Dict = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(lowercase__ , lowercase__ , "tf" ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = FeatureExtractionPipeline(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] SCREAMING_SNAKE_CASE_ : Any = infer_shapes(lowercase__ , lowercase__ ) # Assert all variables are present self.assertEqual(len(lowercase__ ) , len(lowercase__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , lowercase__ ) self.assertSequenceEqual(variable_names[3:] , lowercase__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = ["input_ids", "attention_mask", "token_type_ids"] SCREAMING_SNAKE_CASE_ : Dict = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} SCREAMING_SNAKE_CASE_ : Optional[int] = ensure_valid_input(FuncContiguousArgs() , lowercase__ , lowercase__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(lowercase__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(lowercase__ ) , set(lowercase__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(lowercase__ , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) SCREAMING_SNAKE_CASE_ : Tuple = ensure_valid_input(FuncNonContiguousArgs() , lowercase__ , lowercase__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(lowercase__ ) , 1 ) self.assertEqual(len(lowercase__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
711
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
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 from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## snake_case_ : Any = 1_6 snake_case_ : List[Any] = 3_2 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : int = 1_6 ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_ : str = load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE_ : List[str] ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) 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(): SCREAMING_SNAKE_CASE_ : List[Any] = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , 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 SCREAMING_SNAKE_CASE_ : Dict = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE_ : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_ : Dict = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_ : Any = 1_6 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_ : Dict = 8 else: SCREAMING_SNAKE_CASE_ : List[Any] = None return tokenizer.pad( SCREAMING_SNAKE_CASE_ , padding="longest" , max_length=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : List[Any] = DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) 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 snake_case_ : Optional[int] = mocked_dataloaders # noqa: F811 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ) -> Optional[int]: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE_ ) == "1": SCREAMING_SNAKE_CASE_ : Dict = 2 # New Code # SCREAMING_SNAKE_CASE_ : Optional[Any] = int(args.gradient_accumulation_steps ) SCREAMING_SNAKE_CASE_ : str = int(args.local_sgd_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=SCREAMING_SNAKE_CASE_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : Optional[int] = config["lr"] SCREAMING_SNAKE_CASE_ : Optional[int] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_ : Optional[int] = int(config["seed"] ) SCREAMING_SNAKE_CASE_ : Dict = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_ : Tuple = evaluate.load("glue" , "mrpc" ) set_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : int = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=SCREAMING_SNAKE_CASE_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_ : Any = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : Tuple = AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE_ : Any = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=1_0_0 , num_training_steps=(len(SCREAMING_SNAKE_CASE_ ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE_ ): model.train() with LocalSGD( accelerator=SCREAMING_SNAKE_CASE_ , model=SCREAMING_SNAKE_CASE_ , local_sgd_steps=SCREAMING_SNAKE_CASE_ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = output.loss accelerator.backward(SCREAMING_SNAKE_CASE_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=SCREAMING_SNAKE_CASE_ , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument( "--local_sgd_steps" , type=SCREAMING_SNAKE_CASE_ , default=8 , help="Number of local SGD steps or None to disable local SGD" ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) SCREAMING_SNAKE_CASE_ : Tuple = parser.parse_args() SCREAMING_SNAKE_CASE_ : Any = {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
712
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} snake_case_ = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } snake_case_ = { 'roberta-base': 5_1_2, 'roberta-large': 5_1_2, 'roberta-large-mnli': 5_1_2, 'distilroberta-base': 5_1_2, 'roberta-base-openai-detector': 5_1_2, 'roberta-large-openai-detector': 5_1_2, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] _A = RobertaTokenizer def __init__( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="replace" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="</s>" , lowercase__="<s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__=False , lowercase__=True , **lowercase__ , ): """simple docstring""" super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , errors=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , sep_token=lowercase__ , cls_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , mask_token=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase__ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = add_prefix_space SCREAMING_SNAKE_CASE_ : str = pre_tok_class(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = add_prefix_space SCREAMING_SNAKE_CASE_ : Union[str, Any] = "post_processor" SCREAMING_SNAKE_CASE_ : Union[str, Any] = getattr(self.backend_tokenizer , lowercase__ , lowercase__ ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE_ : Optional[int] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(state["sep"] ) if "cls" in state: SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(state["cls"] ) SCREAMING_SNAKE_CASE_ : Optional[int] = False if state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : Dict = add_prefix_space SCREAMING_SNAKE_CASE_ : Any = True if state.get("trim_offsets" , lowercase__ ) != trim_offsets: SCREAMING_SNAKE_CASE_ : Optional[int] = trim_offsets SCREAMING_SNAKE_CASE_ : Tuple = True if changes_to_apply: SCREAMING_SNAKE_CASE_ : Optional[int] = getattr(lowercase__ , state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : str = component_class(**lowercase__ ) setattr(self.backend_tokenizer , lowercase__ , lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else value SCREAMING_SNAKE_CASE_ : List[str] = value def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.get("is_split_into_words" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get("is_split_into_words" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Optional[int] = [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]
713
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
714
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
0
import math import sys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = "" try: with open(SCREAMING_SNAKE_CASE_ , "rb" ) as binary_file: SCREAMING_SNAKE_CASE_ : List[Any] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE_ : List[str] = F"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = {"0": "0", "1": "1"} SCREAMING_SNAKE_CASE_ : List[str] = "", "" SCREAMING_SNAKE_CASE_ : Dict = len(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE_ : Optional[int] = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE_ : int = last_match_id + "0" if math.loga(SCREAMING_SNAKE_CASE_ ).is_integer(): SCREAMING_SNAKE_CASE_ : List[str] = {} for curr_key in list(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : str = lexicon.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = new_lex SCREAMING_SNAKE_CASE_ : Optional[Any] = last_match_id + "1" index += 1 SCREAMING_SNAKE_CASE_ : List[Any] = "" return result def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 8 try: with open(SCREAMING_SNAKE_CASE_ , "wb" ) as opened_file: SCREAMING_SNAKE_CASE_ : List[Any] = [ to_write[i : i + byte_length] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(SCREAMING_SNAKE_CASE_ , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE_ : Dict = data_bits[counter:] SCREAMING_SNAKE_CASE_ : str = data_bits[counter + 1 :] return data_bits def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = read_file_binary(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = remove_prefix(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = decompress_data(SCREAMING_SNAKE_CASE_ ) write_file_binary(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
715
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
0
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand snake_case_ = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) snake_case_ = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) snake_case_ = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) snake_case_ = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) snake_case_ = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 1_4]), ('2H 5D 3C AS 5S', False, [1_4, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) snake_case_ = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) snake_case_ = ( ('JH AH TH KH QH', 2_3), ('JH 9H TH KH QH', 2_2), ('JC KH JS JD JH', 2_1), ('KH KC 3S 3H 3D', 2_0), ('8C 9C 5C 3C TC', 1_9), ('JS QS 9H TS KH', 1_8), ('7C 7S KH 2H 7H', 1_7), ('3C KH 5D 5S KH', 1_6), ('QH 8H KD JH 8S', 1_5), ('2D 6D 9D TH 7D', 1_4), ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = randrange(len(SCREAMING_SNAKE_CASE_ ) ), randrange(len(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : List[Any] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] SCREAMING_SNAKE_CASE_ : Optional[int] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int = 1_0_0 ) -> Any: """simple docstring""" return (generate_random_hand() for _ in range(SCREAMING_SNAKE_CASE_ )) @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> List[str]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = PokerHand(SCREAMING_SNAKE_CASE_ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int ) -> str: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected def __lowerCamelCase ( ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [PokerHand(SCREAMING_SNAKE_CASE_ ) for hand in SORTED_HANDS] SCREAMING_SNAKE_CASE_ : Optional[int] = poker_hands.copy() shuffle(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = chain(sorted(SCREAMING_SNAKE_CASE_ ) ) for index, hand in enumerate(SCREAMING_SNAKE_CASE_ ): assert hand == poker_hands[index] def __lowerCamelCase ( ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=SCREAMING_SNAKE_CASE_ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = PokerHand("2C 4S AS 3D 5C" ) SCREAMING_SNAKE_CASE_ : List[Any] = True SCREAMING_SNAKE_CASE_ : Tuple = [5, 4, 3, 2, 1_4] for _ in range(1_0 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __lowerCamelCase ( ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = os.path.abspath(os.path.dirname(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , "poker_hands.txt" ) with open(SCREAMING_SNAKE_CASE_ ) as file_hand: for line in file_hand: SCREAMING_SNAKE_CASE_ : str = line[:1_4].strip() SCREAMING_SNAKE_CASE_ : Optional[int] = line[1_5:].strip() SCREAMING_SNAKE_CASE_ : str = PokerHand(SCREAMING_SNAKE_CASE_ ), PokerHand(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = player.compare_with(SCREAMING_SNAKE_CASE_ ) if output == "Win": answer += 1 assert answer == 3_7_6
716
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import sys snake_case_ = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 1 for digit in s: product *= int(SCREAMING_SNAKE_CASE_ ) return product def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str = N ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = -sys.maxsize - 1 SCREAMING_SNAKE_CASE_ : str = n[:1_3] SCREAMING_SNAKE_CASE_ : str = 1_3 while cur_index < len(SCREAMING_SNAKE_CASE_ ) - 1_3: if int(n[cur_index] ) >= int(substr[0] ): SCREAMING_SNAKE_CASE_ : Any = substr[1:] + n[cur_index] cur_index += 1 else: SCREAMING_SNAKE_CASE_ : Dict = max(SCREAMING_SNAKE_CASE_ , str_eval(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : Dict = n[cur_index : cur_index + 1_3] cur_index += 1_3 return largest_product if __name__ == "__main__": print(F'''{solution() = }''')
717
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
718
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> bool: """simple docstring""" return len(set(SCREAMING_SNAKE_CASE_ ) ) == len(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
719
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
0
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = tmp_path / "file.csv" SCREAMING_SNAKE_CASE_ : str = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20\n " ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return str(SCREAMING_SNAKE_CASE_ ) @pytest.fixture def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = tmp_path / "malformed_file.csv" SCREAMING_SNAKE_CASE_ : Any = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20,\n " ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return str(SCREAMING_SNAKE_CASE_ ) @pytest.fixture def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = tmp_path / "csv_with_image.csv" SCREAMING_SNAKE_CASE_ : Any = textwrap.dedent( F"\\n image\n {image_file}\n " ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return str(SCREAMING_SNAKE_CASE_ ) @pytest.fixture def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = tmp_path / "csv_with_label.csv" SCREAMING_SNAKE_CASE_ : Optional[int] = textwrap.dedent( "\\n label\n good\n bad\n good\n " ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return str(SCREAMING_SNAKE_CASE_ ) @pytest.fixture def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = tmp_path / "csv_with_int_list.csv" SCREAMING_SNAKE_CASE_ : Optional[Any] = textwrap.dedent( "\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n " ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return str(SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Csv() SCREAMING_SNAKE_CASE_ : int = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(SCREAMING_SNAKE_CASE_ , match="Error tokenizing data" ): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(SCREAMING_SNAKE_CASE_ ) in record.message for record in caplog.records ) @require_pil def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.read().splitlines()[1] SCREAMING_SNAKE_CASE_ : List[Any] = Csv(encoding="utf-8" , features=Features({"image": Image()} ) ) SCREAMING_SNAKE_CASE_ : List[Any] = csv._generate_tables([[csv_file_with_image]] ) SCREAMING_SNAKE_CASE_ : Dict = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("image" ).type == Image()() SCREAMING_SNAKE_CASE_ : Tuple = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> str: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[str] = f.read().splitlines()[1:] SCREAMING_SNAKE_CASE_ : Optional[int] = Csv(encoding="utf-8" , features=Features({"label": ClassLabel(names=["good", "bad"] )} ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = csv._generate_tables([[csv_file_with_label]] ) SCREAMING_SNAKE_CASE_ : Optional[int] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("label" ).type == ClassLabel(names=["good", "bad"] )() SCREAMING_SNAKE_CASE_ : Optional[int] = pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"] ).straint(SCREAMING_SNAKE_CASE_ ) for label in labels] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Csv(encoding="utf-8" , sep="," , converters={"int_list": lambda SCREAMING_SNAKE_CASE_ : [int(SCREAMING_SNAKE_CASE_ ) for i in x.split()]} ) SCREAMING_SNAKE_CASE_ : Dict = csv._generate_tables([[csv_file_with_int_list]] ) SCREAMING_SNAKE_CASE_ : int = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("int_list" ).type ) SCREAMING_SNAKE_CASE_ : List[str] = pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
720
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
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 snake_case_ = logging.get_logger(__name__) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) snake_case_ = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = 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'), ] ) snake_case_ = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) snake_case_ = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) snake_case_ = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_MAPPING snake_case_ = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_PRETRAINING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_MASKED_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
721
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
0
'''simple docstring''' snake_case_ = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} snake_case_ = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict[int, list[int]] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[bool] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ : Optional[int] = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) order.append(SCREAMING_SNAKE_CASE_ ) return order def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict[int, list[int]] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[bool] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = True SCREAMING_SNAKE_CASE_ : List[Any] = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return component def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict[int, list[int]] ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) * [False] SCREAMING_SNAKE_CASE_ : dict[int, list[int]] = {vert: [] for vert in range(len(SCREAMING_SNAKE_CASE_ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = [] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE_ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE_ : Dict = order[len(SCREAMING_SNAKE_CASE_ ) - i - 1] if not visited[vert]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = find_components(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) components_list.append(SCREAMING_SNAKE_CASE_ ) return components_list
700
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
701
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available snake_case_ = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
0
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py snake_case_ = 'src/transformers' snake_case_ = 'docs/source/en/tasks' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Union[str, Any]: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: SCREAMING_SNAKE_CASE_ : int = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : Tuple = 0 while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_ ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : List[Any] = start_index while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. snake_case_ = direct_transformers_import(TRANSFORMERS_PATH) snake_case_ = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). snake_case_ = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = TASK_GUIDE_TO_MODELS[task_guide] SCREAMING_SNAKE_CASE_ : Optional[int] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(SCREAMING_SNAKE_CASE_ , set() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F"[{name}](../model_doc/{code})" for code, name in model_names.items()] ) + "\n" def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any]=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = _find_text_in_file( filename=os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , start_prompt="<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->" , end_prompt="<!--End of the generated tip-->" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = get_model_list_for_task(SCREAMING_SNAKE_CASE_ ) if current_list != new_list: if overwrite: with open(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`" " to fix this." ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') snake_case_ = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
703
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
704
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "Salesforce/blip-image-captioning-base" _A = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) _A = "image_captioner" _A = AutoModelForVisionaSeq _A = ["image"] _A = ["text"] def __init__( self , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.pre_processor(images=lowercase__ , return_tensors="pt" ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.model.generate(**lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.pre_processor.batch_decode(lowercase__ , skip_special_tokens=lowercase__ )[0].strip()
705
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
0
'''simple docstring''' import math import os import sys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = "" try: with open(SCREAMING_SNAKE_CASE_ , "rb" ) as binary_file: SCREAMING_SNAKE_CASE_ : int = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE_ : Optional[Any] = F"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict[str, str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" lexicon.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = last_match_id if math.loga(SCREAMING_SNAKE_CASE_ ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE_ : List[str] = "0" + lexicon[curr_key] SCREAMING_SNAKE_CASE_ : int = bin(SCREAMING_SNAKE_CASE_ )[2:] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {"0": "0", "1": "1"} SCREAMING_SNAKE_CASE_ : str = "", "" SCREAMING_SNAKE_CASE_ : Any = len(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE_ : Tuple = lexicon[curr_string] result += last_match_id add_key_to_lexicon(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) index += 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE_ : int = lexicon[curr_string] result += last_match_id return result def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = os.path.getsize(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = bin(SCREAMING_SNAKE_CASE_ )[2:] SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) return "0" * (length_length - 1) + file_length_binary + compressed def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 8 try: with open(SCREAMING_SNAKE_CASE_ , "wb" ) as opened_file: SCREAMING_SNAKE_CASE_ : Tuple = [ to_write[i : i + byte_length] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(SCREAMING_SNAKE_CASE_ , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = read_file_binary(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = compress_data(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = add_file_length(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) write_file_binary(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
706
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
0
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
707
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "cvt" def __init__( self , lowercase__=3 , lowercase__=[7, 3, 3] , lowercase__=[4, 2, 2] , lowercase__=[2, 1, 1] , lowercase__=[64, 192, 384] , lowercase__=[1, 3, 6] , lowercase__=[1, 2, 10] , lowercase__=[4.0, 4.0, 4.0] , lowercase__=[0.0, 0.0, 0.0] , lowercase__=[0.0, 0.0, 0.0] , lowercase__=[0.0, 0.0, 0.1] , lowercase__=[True, True, True] , lowercase__=[False, False, True] , lowercase__=["dw_bn", "dw_bn", "dw_bn"] , lowercase__=[3, 3, 3] , lowercase__=[1, 1, 1] , lowercase__=[2, 2, 2] , lowercase__=[1, 1, 1] , lowercase__=[1, 1, 1] , lowercase__=0.02 , lowercase__=1e-12 , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = patch_sizes SCREAMING_SNAKE_CASE_ : List[Any] = patch_stride SCREAMING_SNAKE_CASE_ : Dict = patch_padding SCREAMING_SNAKE_CASE_ : Tuple = embed_dim SCREAMING_SNAKE_CASE_ : Tuple = num_heads SCREAMING_SNAKE_CASE_ : str = depth SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : str = attention_drop_rate SCREAMING_SNAKE_CASE_ : Optional[int] = drop_rate SCREAMING_SNAKE_CASE_ : Optional[int] = drop_path_rate SCREAMING_SNAKE_CASE_ : List[str] = qkv_bias SCREAMING_SNAKE_CASE_ : Any = cls_token SCREAMING_SNAKE_CASE_ : Tuple = qkv_projection_method SCREAMING_SNAKE_CASE_ : Dict = kernel_qkv SCREAMING_SNAKE_CASE_ : Dict = padding_kv SCREAMING_SNAKE_CASE_ : Optional[Any] = stride_kv SCREAMING_SNAKE_CASE_ : Optional[int] = padding_q SCREAMING_SNAKE_CASE_ : Tuple = stride_q SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Dict = layer_norm_eps
708
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
0
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
709
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ) )
68
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = StableUnCLIPImgaImgPipeline _A = TEXT_GUIDED_IMAGE_VARIATION_PARAMS _A = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _A = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _A = frozenset([] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 32 SCREAMING_SNAKE_CASE_ : List[Any] = embedder_hidden_size # image encoding components SCREAMING_SNAKE_CASE_ : int = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Any = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=lowercase__ , projection_dim=lowercase__ , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = StableUnCLIPImageNormalizer(embedding_dim=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowercase__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Dict = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=lowercase__ , layers_per_block=1 , upcast_attention=lowercase__ , use_linear_projection=lowercase__ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.00085 , beta_end=0.012 , prediction_type="v_prediction" , set_alpha_to_one=lowercase__ , steps_offset=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoencoderKL() SCREAMING_SNAKE_CASE_ : Tuple = { # image encoding components "feature_extractor": feature_extractor, "image_encoder": image_encoder.eval(), # image noising components "image_normalizer": image_normalizer.eval(), "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder.eval(), "unet": unet.eval(), "scheduler": scheduler, "vae": vae.eval(), } return components def __lowerCamelCase ( self , lowercase__ , lowercase__=0 , lowercase__=True ): """simple docstring""" if str(lowercase__ ).startswith("mps" ): SCREAMING_SNAKE_CASE_ : Optional[int] = torch.manual_seed(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) if pil_image: SCREAMING_SNAKE_CASE_ : Optional[Any] = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE_ : List[Any] = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE_ : int = DiffusionPipeline.numpy_to_pil(lowercase__ )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Any = StableUnCLIPImgaImgPipeline(**lowercase__ ) SCREAMING_SNAKE_CASE_ : int = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = self.get_dummy_inputs(lowercase__ ) inputs.update({"image_embeds": None} ) SCREAMING_SNAKE_CASE_ : Dict = sd_pipe(**lowercase__ ).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_ : Any = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch_device in ["cpu", "mps"] self._test_attention_slicing_forward_pass(test_max_difference=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=lowercase__ ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __lowerCamelCase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowercase__ ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa ) pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(lowercase__ , "anime turle" , generator=lowercase__ , output_type="np" ) SCREAMING_SNAKE_CASE_ : str = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) SCREAMING_SNAKE_CASE_ : List[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" ) SCREAMING_SNAKE_CASE_ : int = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : int = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(lowercase__ , "anime turle" , generator=lowercase__ , output_type="np" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE_ : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ : Dict = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : List[Any] = pipe( lowercase__ , "anime turtle" , num_inference_steps=2 , output_type="np" , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
710
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_), (SCREAMING_SNAKE_CASE_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
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 snake_case_ = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = [file for file in os.listdir(lowercase__ ) if os.path.isfile(os.path.join(lowercase__ , lowercase__ ) )] if identifier is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowercase__ , lowercase__ ): for n_ in n_identifier: SCREAMING_SNAKE_CASE_ : List[str] = [file for file in files if n_ not in file] else: SCREAMING_SNAKE_CASE_ : Any = [file for file in files if n_identifier not in file] SCREAMING_SNAKE_CASE_ : str = ignore_files or [] ignore_files.append("__init__.py" ) SCREAMING_SNAKE_CASE_ : Optional[int] = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , lowercase__ ) if only_modules: SCREAMING_SNAKE_CASE_ : Optional[Any] = file.split("." )[0] try: SCREAMING_SNAKE_CASE_ : List[str] = getattr(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = doctest.DocTestSuite(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = unittest.TextTestRunner().run(lowercase__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F"{module_identifier} is not a module." ) else: SCREAMING_SNAKE_CASE_ : List[str] = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = Path("src/transformers" ) SCREAMING_SNAKE_CASE_ : str = "modeling" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(lowercase__ , identifier=lowercase__ , ignore_files=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Path("src/transformers" ) SCREAMING_SNAKE_CASE_ : Optional[int] = "tokenization" self.analyze_directory(lowercase__ , identifier=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = Path("src/transformers" ) SCREAMING_SNAKE_CASE_ : Tuple = "configuration" self.analyze_directory(lowercase__ , identifier=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path("src/transformers" ) SCREAMING_SNAKE_CASE_ : Dict = ["configuration", "modeling", "tokenization"] self.analyze_directory(lowercase__ , n_identifier=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Path("docs/source" ) SCREAMING_SNAKE_CASE_ : Any = ["favicon.ico"] self.analyze_directory(lowercase__ , ignore_files=lowercase__ , only_modules=lowercase__ )
711
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> List[str]: """simple docstring""" assert x is not None assert y is not None SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = len(SCREAMING_SNAKE_CASE_ ) # declaring the array for storing the dp values SCREAMING_SNAKE_CASE_ : int = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 , m + 1 ): for j in range(1 , n + 1 ): SCREAMING_SNAKE_CASE_ : Any = 1 if x[i - 1] == y[j - 1] else 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match ) SCREAMING_SNAKE_CASE_ : Optional[int] = "" SCREAMING_SNAKE_CASE_ : int = m, n while i > 0 and j > 0: SCREAMING_SNAKE_CASE_ : Any = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: SCREAMING_SNAKE_CASE_ : List[str] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": snake_case_ : int = 'AGGTAB' snake_case_ : Optional[int] = 'GXTXAYB' snake_case_ : str = 4 snake_case_ : int = 'GTAB' snake_case_ , snake_case_ : int = longest_common_subsequence(a, b) print('len =', ln, ', sub-sequence =', subseq) import doctest doctest.testmod()
712
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
0
'''simple docstring''' import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = botoa.client("iam" ) SCREAMING_SNAKE_CASE_ : List[Any] = { "Version": "2012-10-17", "Statement": [ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=SCREAMING_SNAKE_CASE_ , AssumeRolePolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 ) ) SCREAMING_SNAKE_CASE_ : Tuple = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:*", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability", "ecr:GetAuthorizationToken", "cloudwatch:PutMetricData", "cloudwatch:GetMetricData", "cloudwatch:GetMetricStatistics", "cloudwatch:ListMetrics", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "s3:CreateBucket", "s3:ListBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", ], "Resource": "*", } ], } # attach policy to role iam_client.put_role_policy( RoleName=SCREAMING_SNAKE_CASE_ , PolicyName=F"{role_name}_policy_permission" , PolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F"role {role_name} already exists. Using existing one" ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = botoa.client("iam" ) return iam_client.get_role(RoleName=SCREAMING_SNAKE_CASE_ )["Role"]["Arn"] def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = _ask_options( "How do you want to authorize?" , ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "] , SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if credentials_configuration == 0: SCREAMING_SNAKE_CASE_ : Dict = _ask_field("Enter your AWS Profile name: [default] " , default="default" ) SCREAMING_SNAKE_CASE_ : Dict = aws_profile else: print( "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" ) SCREAMING_SNAKE_CASE_ : Optional[int] = _ask_field("AWS Access Key ID: " ) SCREAMING_SNAKE_CASE_ : Optional[Any] = aws_access_key_id SCREAMING_SNAKE_CASE_ : Tuple = _ask_field("AWS Secret Access Key: " ) SCREAMING_SNAKE_CASE_ : Dict = aws_secret_access_key SCREAMING_SNAKE_CASE_ : Any = _ask_field("Enter your AWS Region: [us-east-1]" , default="us-east-1" ) SCREAMING_SNAKE_CASE_ : Any = aws_region SCREAMING_SNAKE_CASE_ : List[Any] = _ask_options( "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?" , ["Provide IAM Role name", "Create new IAM role using credentials"] , SCREAMING_SNAKE_CASE_ , ) if role_management == 0: SCREAMING_SNAKE_CASE_ : List[Any] = _ask_field("Enter your IAM role name: " ) else: SCREAMING_SNAKE_CASE_ : Tuple = "accelerate_sagemaker_execution_role" print(F"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = _ask_field( "Do you want to use custom Docker image? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = None if is_custom_docker_image: SCREAMING_SNAKE_CASE_ : Any = _ask_field("Enter your Docker image: " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() ) SCREAMING_SNAKE_CASE_ : str = _ask_field( "Do you want to provide SageMaker input channels with data locations? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Tuple = None if is_sagemaker_inputs_enabled: SCREAMING_SNAKE_CASE_ : List[Any] = _ask_field( "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , ) SCREAMING_SNAKE_CASE_ : Any = _ask_field( "Do you want to enable SageMaker metrics? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Tuple = None if is_sagemaker_metrics_enabled: SCREAMING_SNAKE_CASE_ : int = _ask_field( "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , ) SCREAMING_SNAKE_CASE_ : int = _ask_options( "What is the distributed mode?" , ["No distributed training", "Data parallelism"] , _convert_sagemaker_distributed_mode , ) SCREAMING_SNAKE_CASE_ : Any = {} SCREAMING_SNAKE_CASE_ : str = _ask_field( "Do you wish to optimize your script with torch dynamo?[yes/NO]:" , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) if use_dynamo: SCREAMING_SNAKE_CASE_ : Union[str, Any] = "dynamo_" SCREAMING_SNAKE_CASE_ : Dict = _ask_options( "Which dynamo backend would you like to use?" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) SCREAMING_SNAKE_CASE_ : int = _ask_field( "Do you want to customize the defaults sent to torch.compile? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) if use_custom_options: SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_options( "Which mode do you want to use?" , SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : TORCH_DYNAMO_MODES[int(SCREAMING_SNAKE_CASE_ )] , default="default" , ) SCREAMING_SNAKE_CASE_ : Tuple = _ask_field( "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_field( "Do you want to enable dynamic shape tracing? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Dict = "Which EC2 instance type you want to use for your training?" if distributed_type != SageMakerDistributedType.NO: SCREAMING_SNAKE_CASE_ : List[str] = _ask_options( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(SCREAMING_SNAKE_CASE_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" SCREAMING_SNAKE_CASE_ : Optional[int] = _ask_field(SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , default="ml.p3.2xlarge" ) SCREAMING_SNAKE_CASE_ : Optional[int] = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): SCREAMING_SNAKE_CASE_ : Optional[Any] = _ask_field( "How many machines do you want use? [1]: " , SCREAMING_SNAKE_CASE_ , default=1 , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_options( "Do you wish to use FP16 or BF16 (mixed precision)?" , ["no", "fp16", "bf16", "fp8"] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." ) return SageMakerConfig( image_uri=SCREAMING_SNAKE_CASE_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=SCREAMING_SNAKE_CASE_ , use_cpu=SCREAMING_SNAKE_CASE_ , dynamo_config=SCREAMING_SNAKE_CASE_ , eca_instance_type=SCREAMING_SNAKE_CASE_ , profile=SCREAMING_SNAKE_CASE_ , region=SCREAMING_SNAKE_CASE_ , iam_role_name=SCREAMING_SNAKE_CASE_ , mixed_precision=SCREAMING_SNAKE_CASE_ , num_machines=SCREAMING_SNAKE_CASE_ , sagemaker_inputs_file=SCREAMING_SNAKE_CASE_ , sagemaker_metrics_file=SCREAMING_SNAKE_CASE_ , )
713
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Any ) -> Union[str, Any]: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE_ : Tuple = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Exception ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [ "CUDA out of memory.", # CUDA OOM "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU "DefaultCPUAllocator: can't allocate memory", # CPU OOM ] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : callable = None , SCREAMING_SNAKE_CASE_ : int = 1_2_8 ) -> Tuple: """simple docstring""" if function is None: return functools.partial(SCREAMING_SNAKE_CASE_ , starting_batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = starting_batch_size def decorator(*SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE_ : Optional[int] = list(inspect.signature(SCREAMING_SNAKE_CASE_ ).parameters.keys() ) # Guard against user error if len(SCREAMING_SNAKE_CASE_ ) < (len(SCREAMING_SNAKE_CASE_ ) + 1): SCREAMING_SNAKE_CASE_ : Tuple = ", ".join([F"{arg}={value}" for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F"Batch size was passed into `{function.__name__}` as the first argument when called." F"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" ) while True: if batch_size == 0: raise RuntimeError("No executable batch size found, reached zero." ) try: return function(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) except Exception as e: if should_reduce_batch_size(SCREAMING_SNAKE_CASE_ ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
714
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters snake_case_ = (7_2_0, 1_2_8_0) # Height, Width snake_case_ = (0.4, 0.6) # if height or width lower than this scale, drop it. snake_case_ = 1 / 1_0_0 snake_case_ = '' snake_case_ = '' snake_case_ = '' snake_case_ = 2_5_0 def __lowerCamelCase ( ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_dataset(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for index in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : str = random.sample(range(len(SCREAMING_SNAKE_CASE_ ) ) , 4 ) SCREAMING_SNAKE_CASE_ : Tuple = update_image_and_anno( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , filter_scale=SCREAMING_SNAKE_CASE_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE_ : int = random_chars(3_2 ) SCREAMING_SNAKE_CASE_ : List[str] = path.split(os.sep )[-1].rsplit("." , 1 )[0] SCREAMING_SNAKE_CASE_ : Optional[int] = F"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cva.imwrite(F"{file_root}.jpg" , SCREAMING_SNAKE_CASE_ , [cva.IMWRITE_JPEG_QUALITY, 8_5] ) print(F"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}" ) SCREAMING_SNAKE_CASE_ : List[str] = [] for anno in new_annos: SCREAMING_SNAKE_CASE_ : Dict = anno[3] - anno[1] SCREAMING_SNAKE_CASE_ : Optional[int] = anno[4] - anno[2] SCREAMING_SNAKE_CASE_ : Optional[Any] = anno[1] + width / 2 SCREAMING_SNAKE_CASE_ : Tuple = anno[2] + height / 2 SCREAMING_SNAKE_CASE_ : int = F"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(SCREAMING_SNAKE_CASE_ ) with open(F"{file_root}.txt" , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> tuple[list, list]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Any = [] for label_file in glob.glob(os.path.join(SCREAMING_SNAKE_CASE_ , "*.txt" ) ): SCREAMING_SNAKE_CASE_ : List[str] = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(SCREAMING_SNAKE_CASE_ ) as in_file: SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_file.readlines() SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(SCREAMING_SNAKE_CASE_ , F"{label_name}.jpg" ) SCREAMING_SNAKE_CASE_ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE_ : Optional[Any] = obj_list.rstrip("\n" ).split(" " ) SCREAMING_SNAKE_CASE_ : Tuple = float(obj[1] ) - float(obj[3] ) / 2 SCREAMING_SNAKE_CASE_ : List[Any] = float(obj[2] ) - float(obj[4] ) / 2 SCREAMING_SNAKE_CASE_ : Any = float(obj[1] ) + float(obj[3] ) / 2 SCREAMING_SNAKE_CASE_ : Any = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(SCREAMING_SNAKE_CASE_ ) labels.append(SCREAMING_SNAKE_CASE_ ) return img_paths, labels def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : tuple[int, int] , SCREAMING_SNAKE_CASE_ : tuple[float, float] , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE_ : Optional[int] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE_ : Any = int(scale_x * output_size[1] ) SCREAMING_SNAKE_CASE_ : str = int(scale_y * output_size[0] ) SCREAMING_SNAKE_CASE_ : Dict = [] SCREAMING_SNAKE_CASE_ : List[str] = [] for i, index in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : List[Any] = all_img_list[index] path_list.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = all_annos[index] SCREAMING_SNAKE_CASE_ : int = cva.imread(SCREAMING_SNAKE_CASE_ ) if i == 0: # top-left SCREAMING_SNAKE_CASE_ : Optional[Any] = cva.resize(SCREAMING_SNAKE_CASE_ , (divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[1] * scale_x SCREAMING_SNAKE_CASE_ : List[str] = bbox[2] * scale_y SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[3] * scale_x SCREAMING_SNAKE_CASE_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right SCREAMING_SNAKE_CASE_ : Tuple = cva.resize(SCREAMING_SNAKE_CASE_ , (output_size[1] - divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE_ : Tuple = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Any = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : Optional[Any] = bbox[2] * scale_y SCREAMING_SNAKE_CASE_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : Dict = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left SCREAMING_SNAKE_CASE_ : List[str] = cva.resize(SCREAMING_SNAKE_CASE_ , (divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[1] * scale_x SCREAMING_SNAKE_CASE_ : Optional[Any] = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE_ : List[Any] = bbox[3] * scale_x SCREAMING_SNAKE_CASE_ : Union[str, Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right SCREAMING_SNAKE_CASE_ : Optional[Any] = cva.resize( SCREAMING_SNAKE_CASE_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : int = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : List[Any] = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : List[Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: SCREAMING_SNAKE_CASE_ : Any = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE_ : Tuple = ascii_lowercase + digits return "".join(random.choice(SCREAMING_SNAKE_CASE_ ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": main() print('DONE ✅')
715
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = TFCamembertModel.from_pretrained("jplu/tf-camembert-base" ) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ )["last_hidden_state"] SCREAMING_SNAKE_CASE_ : Any = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , lowercase__ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE_ : Dict = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
716
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
0
'''simple docstring''' import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = LxmertConfig.from_json_file(SCREAMING_SNAKE_CASE_ ) print(F"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_ : int = LxmertForPreTraining(SCREAMING_SNAKE_CASE_ ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) snake_case_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
717
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
0
'''simple docstring''' import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig snake_case_ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "maskformer" _A = {"hidden_size": "mask_feature_size"} _A = ["resnet", "swin"] _A = ["detr"] def __init__( self , lowercase__ = 256 , lowercase__ = 256 , lowercase__ = 0.1 , lowercase__ = False , lowercase__ = None , lowercase__ = None , lowercase__ = 0.02 , lowercase__ = 1.0 , lowercase__ = 1.0 , lowercase__ = 1.0 , lowercase__ = 20.0 , lowercase__ = None , **lowercase__ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ : List[Any] = SwinConfig( image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = backbone_config.pop("model_type" ) SCREAMING_SNAKE_CASE_ : Any = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ : Optional[int] = config_class.from_dict(lowercase__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. " F"Supported model types: {','.join(self.backbones_supported )}" ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ : Tuple = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ : Optional[Any] = ( decoder_config.pop("model_type" ) if isinstance(lowercase__ , lowercase__ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( F"Transformer Decoder {decoder_type} not supported, please use one of" F" {','.join(self.decoders_supported )}" ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ : Tuple = config_class.from_dict(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = backbone_config SCREAMING_SNAKE_CASE_ : int = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ : Union[str, Any] = fpn_feature_size SCREAMING_SNAKE_CASE_ : Optional[Any] = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ : Optional[int] = init_std SCREAMING_SNAKE_CASE_ : int = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ : str = cross_entropy_weight SCREAMING_SNAKE_CASE_ : List[Any] = dice_weight SCREAMING_SNAKE_CASE_ : Any = mask_weight SCREAMING_SNAKE_CASE_ : Dict = use_auxiliary_loss SCREAMING_SNAKE_CASE_ : Dict = no_object_weight SCREAMING_SNAKE_CASE_ : Optional[int] = output_auxiliary_logits SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = self.decoder_config.num_hidden_layers super().__init__(**lowercase__ ) @classmethod def __lowerCamelCase ( cls , lowercase__ , lowercase__ , **lowercase__ ): """simple docstring""" return cls( backbone_config=lowercase__ , decoder_config=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Dict = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ : int = self.__class__.model_type return output
718
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
0
'''simple docstring''' from __future__ import annotations snake_case_ : Optional[Any] = [True] * 1_0_0_0_0_0_1 snake_case_ : List[Any] = 2 while i * i <= 1_0_0_0_0_0_0: if seive[i]: for j in range(i * i, 1_0_0_0_0_0_1, i): snake_case_ : List[str] = False i += 1 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" return seive[n] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" return any(digit in "02468" for digit in str(SCREAMING_SNAKE_CASE_ ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_0_0 ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(SCREAMING_SNAKE_CASE_ ) and not contains_an_even_digit(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Optional[int] = str(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = [int(str_num[j:] + str_num[:j] ) for j in range(len(SCREAMING_SNAKE_CASE_ ) )] if all(is_prime(SCREAMING_SNAKE_CASE_ ) for i in list_nums ): result.append(SCREAMING_SNAKE_CASE_ ) return result def __lowerCamelCase ( ) -> int: """simple docstring""" return len(find_circular_primes() ) if __name__ == "__main__": print(F'''{len(find_circular_primes()) = }''')
719
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
0
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return 0.0 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int ) -> tuple[int | float, int | float]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = min([-2_0, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_ : int = max([2_0, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : FilterType , SCREAMING_SNAKE_CASE_ : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 5_1_2 SCREAMING_SNAKE_CASE_ : Optional[int] = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_ : int = [filter_type.process(SCREAMING_SNAKE_CASE_ ) for item in inputs] SCREAMING_SNAKE_CASE_ : Any = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_ : Optional[Any] = np.abs(np.fft.fft(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : Dict = 2_0 * np.logaa(SCREAMING_SNAKE_CASE_ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(2_4 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_ : Dict = get_bounds(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) plt.ylim(max([-8_0, bounds[0]] ) , min([8_0, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(SCREAMING_SNAKE_CASE_ ) plt.show() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : FilterType , SCREAMING_SNAKE_CASE_ : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 5_1_2 SCREAMING_SNAKE_CASE_ : Any = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_ : Dict = [filter_type.process(SCREAMING_SNAKE_CASE_ ) for item in inputs] SCREAMING_SNAKE_CASE_ : str = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_ : Any = np.angle(np.fft.fft(SCREAMING_SNAKE_CASE_ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(2_4 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE_ , -2 * pi ) ) plt.show()
720
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
0
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.txt'} snake_case_ = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } snake_case_ = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> List[Any]: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , "r" ) as f: SCREAMING_SNAKE_CASE_ : Tuple = f.read().splitlines() return [l.strip() for l in lines] class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__="<unk>" , lowercase__="<cls>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__="<eos>" , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = load_vocab_file(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = {tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE_ : Any = unk_token SCREAMING_SNAKE_CASE_ : str = cls_token SCREAMING_SNAKE_CASE_ : Dict = pad_token SCREAMING_SNAKE_CASE_ : Tuple = mask_token SCREAMING_SNAKE_CASE_ : Any = eos_token SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self._id_to_token.get(lowercase__ , self.unk_token ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self._token_to_id.get(lowercase__ , self._token_to_id.get(self.unk_token ) ) def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" return text.split() def __lowerCamelCase ( self , lowercase__=False ): """simple docstring""" return len(self._id_to_token ) def __lowerCamelCase ( self ): """simple docstring""" return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self._token_to_id.get(lowercase__ , self._token_to_id.get(self.unk_token ) ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self._id_to_token.get(lowercase__ , self.unk_token ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE_ : Dict = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = False ): """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1] + ([0] * len(lowercase__ )) + [1] if token_ids_a is not None: mask += [0] * len(lowercase__ ) + [1] return mask def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(lowercase__ , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(lowercase__ , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCamelCase ( self ): """simple docstring""" return self.get_vocab_size(with_added_tokens=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" return super()._add_tokens(lowercase__ , special_tokens=lowercase__ )
721
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
0
'''simple docstring''' import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ = 1_6 snake_case_ = 3_2 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> str: """simple docstring""" return int(x / 2**2_0 ) class SCREAMING_SNAKE_CASE__ : def __enter__( self ): """simple docstring""" gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero SCREAMING_SNAKE_CASE_ : int = torch.cuda.memory_allocated() return self def __exit__( self , *lowercase__ ): """simple docstring""" gc.collect() torch.cuda.empty_cache() SCREAMING_SNAKE_CASE_ : Tuple = torch.cuda.memory_allocated() SCREAMING_SNAKE_CASE_ : Any = torch.cuda.max_memory_allocated() SCREAMING_SNAKE_CASE_ : List[str] = bamb(self.end - self.begin ) SCREAMING_SNAKE_CASE_ : Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : int = 1_6 , SCREAMING_SNAKE_CASE_ : str = "bert-base-cased" , SCREAMING_SNAKE_CASE_ : int = 3_2_0 , SCREAMING_SNAKE_CASE_ : int = 1_6_0 , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = load_dataset( "glue" , "mrpc" , split={"train": F"train[:{n_train}]", "validation": F"validation[:{n_val}]"} ) def tokenize_function(SCREAMING_SNAKE_CASE_ : int ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=SCREAMING_SNAKE_CASE_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_ : Dict = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding="max_length" , max_length=1_2_8 , return_tensors="pt" ) return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : List[str] = DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) return train_dataloader, eval_dataloader def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : str = config["lr"] SCREAMING_SNAKE_CASE_ : Optional[int] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_ : Dict = int(config["seed"] ) SCREAMING_SNAKE_CASE_ : Tuple = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_ : int = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE_ : Dict = optimizer_cls(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE_ : int = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = (len(SCREAMING_SNAKE_CASE_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE_ : str = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=0 , num_training_steps=SCREAMING_SNAKE_CASE_ , ) else: SCREAMING_SNAKE_CASE_ : List[str] = DummyScheduler(SCREAMING_SNAKE_CASE_ , total_num_steps=SCREAMING_SNAKE_CASE_ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE_ : List[str] = 0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 # Now we train the model SCREAMING_SNAKE_CASE_ : List[str] = {} for epoch in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Optional[int] = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = outputs.loss SCREAMING_SNAKE_CASE_ : Union[str, Any] = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("Memory before entering the train : {}".format(bamb(tracemalloc.begin ) ) ) accelerator.print("Memory consumed at the end of the train (end-begin): {}".format(tracemalloc.used ) ) accelerator.print("Peak Memory consumed during the train (max-begin): {}".format(tracemalloc.peaked ) ) accelerator.print( "Total Peak Memory consumed during the train (max): {}".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) SCREAMING_SNAKE_CASE_ : Dict = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"epoch-{epoch}"] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , "peak_memory_utilization.json" ) , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=SCREAMING_SNAKE_CASE_ , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=SCREAMING_SNAKE_CASE_ , ) parser.add_argument( "--output_dir" , type=SCREAMING_SNAKE_CASE_ , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--peak_memory_upper_bound" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value." , ) parser.add_argument( "--n_train" , type=SCREAMING_SNAKE_CASE_ , default=3_2_0 , help="Number of training examples to use." , ) parser.add_argument( "--n_val" , type=SCREAMING_SNAKE_CASE_ , default=1_6_0 , help="Number of validation examples to use." , ) parser.add_argument( "--num_epochs" , type=SCREAMING_SNAKE_CASE_ , default=1 , help="Number of train epochs." , ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_ : int = {"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 4_2, "batch_size": 1_6} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
700
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=_UpperCAmelCase ): _A = ["torch", "torchsde"] def __init__( self , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(self , ["torch", "torchsde"] ) @classmethod def __lowerCamelCase ( cls , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(cls , ["torch", "torchsde"] ) @classmethod def __lowerCamelCase ( cls , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(cls , ["torch", "torchsde"] )
701
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
0
'''simple docstring''' import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset snake_case_ = 'bert-base-cased' snake_case_ = 'google/pegasus-xsum' snake_case_ = [' Sam ate lunch today.', 'Sams lunch ingredients.'] snake_case_ = ['A very interesting story about what I ate for lunch.', 'Avocado, celery, turkey, coffee'] snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = 'sshleifer/tiny-marian-en-de' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict ) -> Optional[Any]: """simple docstring""" for split in ["train", "val", "test"]: _dump_articles(os.path.join(SCREAMING_SNAKE_CASE_ , F"{split}.source" ) , SCREAMING_SNAKE_CASE_ ) _dump_articles(os.path.join(SCREAMING_SNAKE_CASE_ , F"{split}.target" ) , SCREAMING_SNAKE_CASE_ ) return tmp_dir class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : str = max(len(tokenizer.encode(lowercase__ ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE_ : Optional[int] = max(len(tokenizer.encode(lowercase__ ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE_ : Dict = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated SCREAMING_SNAKE_CASE_ : Tuple = "ro_RO", "de_DE" # ignored for all but mbart, but never causes error. SCREAMING_SNAKE_CASE_ : str = SeqaSeqDataset( lowercase__ , data_dir=lowercase__ , type_path="train" , max_source_length=lowercase__ , max_target_length=lowercase__ , src_lang=lowercase__ , tgt_lang=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = DataLoader(lowercase__ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(lowercase__ , lowercase__ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place SCREAMING_SNAKE_CASE_ : str = shift_tokens_right(batch["labels"] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Dict = max(len(tokenizer.encode(lowercase__ ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE_ : Any = max(len(tokenizer.encode(lowercase__ ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE_ : Any = LegacySeqaSeqDataset( lowercase__ , data_dir=lowercase__ , type_path="train" , max_source_length=20 , max_target_length=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(lowercase__ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25" ) SCREAMING_SNAKE_CASE_ : Dict = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = tmp_dir.joinpath("train.source" ).open().readlines() SCREAMING_SNAKE_CASE_ : Optional[int] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(lowercase__ , lowercase__ , 128 , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {x.name for x in tmp_dir.iterdir()} SCREAMING_SNAKE_CASE_ : List[Any] = {x.name for x in save_dir.iterdir()} SCREAMING_SNAKE_CASE_ : str = save_dir.joinpath("train.source" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(lowercase__ ) < len(lowercase__ ) assert len(lowercase__ ) == 1 assert len(packed_examples[0] ) == sum(len(lowercase__ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="This test requires fairseq" ) def __lowerCamelCase ( self ): """simple docstring""" if not FAIRSEQ_AVAILABLE: return SCREAMING_SNAKE_CASE_ : List[Any] = self._get_dataset(max_len=64 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 64 SCREAMING_SNAKE_CASE_ : Dict = ds.make_dynamic_sampler(lowercase__ , required_batch_size_multiple=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = [len(lowercase__ ) for x in batch_sampler] assert len(set(lowercase__ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(lowercase__ ) == len(lowercase__ ) # no dropped or added examples SCREAMING_SNAKE_CASE_ : Optional[int] = DataLoader(lowercase__ , batch_sampler=lowercase__ , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE_ : Any = [] SCREAMING_SNAKE_CASE_ : List[Any] = [] for batch in data_loader: SCREAMING_SNAKE_CASE_ : List[str] = batch["input_ids"].shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple SCREAMING_SNAKE_CASE_ : List[str] = np.product(batch["input_ids"].shape ) num_src_per_batch.append(lowercase__ ) if num_src_tokens > (max_tokens * 1.1): failures.append(lowercase__ ) assert num_src_per_batch[0] == max(lowercase__ ) if failures: raise AssertionError(F"too many tokens in {len(lowercase__ )} batches" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self._get_dataset(max_len=512 ) SCREAMING_SNAKE_CASE_ : str = 2 SCREAMING_SNAKE_CASE_ : Dict = ds.make_sortish_sampler(lowercase__ , shuffle=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(lowercase__ , batch_size=lowercase__ , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE_ : str = DataLoader(lowercase__ , batch_size=lowercase__ , collate_fn=ds.collate_fn , num_workers=2 , sampler=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.pad_token_id def count_pad_tokens(lowercase__ , lowercase__="input_ids" ): return [batch[k].eq(lowercase__ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(lowercase__ , k="labels" ) ) < sum(count_pad_tokens(lowercase__ , k="labels" ) ) assert sum(count_pad_tokens(lowercase__ ) ) < sum(count_pad_tokens(lowercase__ ) ) assert len(lowercase__ ) == len(lowercase__ ) def __lowerCamelCase ( self , lowercase__=1000 , lowercase__=128 ): """simple docstring""" if os.getenv("USE_REAL_DATA" , lowercase__ ): SCREAMING_SNAKE_CASE_ : str = "examples/seq2seq/wmt_en_ro" SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_len * 2 * 64 if not Path(lowercase__ ).joinpath("train.len" ).exists(): save_len_file(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = "examples/seq2seq/test_data/wmt_en_ro" SCREAMING_SNAKE_CASE_ : Tuple = max_len * 4 save_len_file(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = SeqaSeqDataset( lowercase__ , data_dir=lowercase__ , type_path="train" , max_source_length=lowercase__ , max_target_length=lowercase__ , n_obs=lowercase__ , ) return ds, max_tokens, tokenizer def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self._get_dataset() SCREAMING_SNAKE_CASE_ : Union[str, Any] = set(DistributedSortishSampler(lowercase__ , 256 , num_replicas=2 , rank=0 , add_extra_examples=lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Any = set(DistributedSortishSampler(lowercase__ , 256 , num_replicas=2 , rank=1 , add_extra_examples=lowercase__ ) ) assert idsa.intersection(lowercase__ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained(lowercase__ , use_fast=lowercase__ ) if tok_name == MBART_TINY: SCREAMING_SNAKE_CASE_ : Tuple = SeqaSeqDataset( lowercase__ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , src_lang="EN" , tgt_lang="FR" , ) SCREAMING_SNAKE_CASE_ : str = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: SCREAMING_SNAKE_CASE_ : str = SeqaSeqDataset( lowercase__ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , ) SCREAMING_SNAKE_CASE_ : Tuple = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(lowercase__ ) == 1 if tok_name == BART_TINY else len(lowercase__ ) == 0
702
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[Any]: """simple docstring""" if "resnet-50" in model_name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ResNetConfig.from_pretrained("microsoft/resnet-50" ) elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE_ : Dict = ResNetConfig.from_pretrained("microsoft/resnet-101" ) else: raise ValueError("Model name should include either resnet50 or resnet101" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = DetrConfig(use_timm_backbone=SCREAMING_SNAKE_CASE_ , backbone_config=SCREAMING_SNAKE_CASE_ ) # set label attributes SCREAMING_SNAKE_CASE_ : Union[str, Any] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2_5_0 else: SCREAMING_SNAKE_CASE_ : Optional[int] = 9_1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = "huggingface/label-files" SCREAMING_SNAKE_CASE_ : Dict = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE_ : Dict = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE_ : Dict = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : int = idalabel SCREAMING_SNAKE_CASE_ : str = {v: k for k, v in idalabel.items()} return config, is_panoptic def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight") ) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight") ) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias") ) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean") ) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F"transformer.encoder.layers.{i}.self_attn.out_proj.weight", F"encoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.encoder.layers.{i}.self_attn.out_proj.bias", F"encoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.weight", F"encoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.bias", F"encoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.weight", F"encoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.bias", F"encoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.weight", F"encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.bias", F"encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm2.weight", F"encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.norm2.bias", F"encoder.layers.{i}.final_layer_norm.bias") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F"transformer.decoder.layers.{i}.self_attn.out_proj.weight", F"decoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.decoder.layers.{i}.self_attn.out_proj.bias", F"decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", F"decoder.layers.{i}.encoder_attn.out_proj.weight", ) ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", F"decoder.layers.{i}.encoder_attn.out_proj.bias", ) ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.weight", F"decoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.bias", F"decoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.weight", F"decoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.bias", F"decoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.weight", F"decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.bias", F"decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.weight", F"decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.bias", F"decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm3.weight", F"decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.norm3.bias", F"decoder.layers.{i}.final_layer_norm.bias") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) return rename_keys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = val def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str=False ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = "" if is_panoptic: SCREAMING_SNAKE_CASE_ : Tuple = "detr." # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : int = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Any = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_weight[:2_5_6, :] SCREAMING_SNAKE_CASE_ : Dict = in_proj_bias[:2_5_6] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_weight[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : Any = in_proj_bias[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_weight[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[-2_5_6:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : Any = in_proj_weight[:2_5_6, :] SCREAMING_SNAKE_CASE_ : int = in_proj_bias[:2_5_6] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_weight[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_bias[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_weight[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[-2_5_6:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop( F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias" ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE_ : int = in_proj_weight_cross_attn[:2_5_6, :] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_bias_cross_attn[:2_5_6] SCREAMING_SNAKE_CASE_ : Dict = in_proj_weight_cross_attn[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_bias_cross_attn[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_weight_cross_attn[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_bias_cross_attn[-2_5_6:] def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = get_detr_config(SCREAMING_SNAKE_CASE_ ) # load original model from torch hub SCREAMING_SNAKE_CASE_ : Tuple = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(F"Converting model {model_name}..." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=SCREAMING_SNAKE_CASE_ ).eval() SCREAMING_SNAKE_CASE_ : List[str] = detr.state_dict() # rename keys for src, dest in create_rename_keys(SCREAMING_SNAKE_CASE_ ): if is_panoptic: SCREAMING_SNAKE_CASE_ : Dict = "detr." + src rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # query, key and value matrices need special treatment read_in_q_k_v(SCREAMING_SNAKE_CASE_ , is_panoptic=SCREAMING_SNAKE_CASE_ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE_ : Optional[int] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr" ) and not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE_ : str = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = val elif key.startswith("bbox_attention" ) or key.startswith("mask_head" ): continue else: SCREAMING_SNAKE_CASE_ : List[str] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = val else: if not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ): SCREAMING_SNAKE_CASE_ : List[Any] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE_ : Tuple = DetrForSegmentation(SCREAMING_SNAKE_CASE_ ) if is_panoptic else DetrForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE_ : List[Any] = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE_ : Optional[Any] = DetrImageProcessor(format=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Dict = encoding["pixel_values"] SCREAMING_SNAKE_CASE_ : List[str] = detr(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = model(SCREAMING_SNAKE_CASE_ ) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub..." ) model.push_to_hub(F"nielsr/{model_name}" ) processor.push_to_hub(F"nielsr/{model_name}" ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') snake_case_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
703
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
0
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = ["pixel_values"] def __init__( self , lowercase__ = True , lowercase__ = None , lowercase__ = PILImageResampling.BILINEAR , lowercase__ = True , lowercase__ = 1 / 255 , lowercase__ = True , lowercase__ = None , lowercase__ = True , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else {"shortest_edge": 224} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase__ , param_name="crop_size" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_resize SCREAMING_SNAKE_CASE_ : Union[str, Any] = size SCREAMING_SNAKE_CASE_ : List[str] = resample SCREAMING_SNAKE_CASE_ : Dict = do_rescale SCREAMING_SNAKE_CASE_ : List[Any] = rescale_factor SCREAMING_SNAKE_CASE_ : Optional[Any] = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : str = do_flip_channel_order def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = PIL.Image.BILINEAR , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = get_size_dict(lowercase__ , default_to_square=lowercase__ ) if "shortest_edge" not in size: raise ValueError(F"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}" ) SCREAMING_SNAKE_CASE_ : List[Any] = 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = get_size_dict(lowercase__ ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" ) return center_crop(lowercase__ , size=(size["height"], size["width"]) , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" return flip_channel_order(lowercase__ , data_format=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = ChannelDimension.FIRST , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : str = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) SCREAMING_SNAKE_CASE_ : Tuple = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase__ , param_name="crop_size" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : Any = [to_numpy_array(lowercase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.resize(image=lowercase__ , size=lowercase__ , resample=lowercase__ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE_ : int = [self.center_crop(image=lowercase__ , size=lowercase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ : str = [self.rescale(image=lowercase__ , scale=lowercase__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.flip_channel_order(image=lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : List[Any] = [to_channel_dimension_format(lowercase__ , lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : int = {"pixel_values": images} return BatchFeature(data=lowercase__ , tensor_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(lowercase__ ) != len(lowercase__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(lowercase__ ): SCREAMING_SNAKE_CASE_ : int = target_sizes.numpy() SCREAMING_SNAKE_CASE_ : List[Any] = [] for idx in range(len(lowercase__ ) ): SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Any = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE_ : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
704
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : Dict = logging.get_logger(__name__) snake_case_ : Tuple = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "roberta-prelayernorm" def __init__( self , lowercase__=5_0265 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = vocab_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Dict = initializer_range SCREAMING_SNAKE_CASE_ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE_ : str = position_embedding_type SCREAMING_SNAKE_CASE_ : Optional[int] = use_cache SCREAMING_SNAKE_CASE_ : List[str] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : List[str] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
705
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ = {'configuration_ibert': ['IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'IBertConfig', 'IBertOnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'IBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'IBertForMaskedLM', 'IBertForMultipleChoice', 'IBertForQuestionAnswering', 'IBertForSequenceClassification', 'IBertForTokenClassification', 'IBertModel', 'IBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
706
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
0