code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import baseaa def a__ ( __UpperCamelCase ): return baseaa.baaencode(string.encode("utf-8" ) ) def a__ ( __UpperCamelCase ): return baseaa.baadecode(__UpperCamelCase ).decode("utf-8" ) if __name__ == "__main__": A : Tuple = "Hello World!" A : List[Any] = baseaa_encode(test) print(encoded) A : List[str] = baseaa_decode(encoded) print(decoded)
118
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline A : Tuple = datasets.utils.logging.get_logger(__name__) @dataclass class lowerCamelCase (datasets.BuilderConfig ): """simple docstring""" lowerCamelCase__ = None lowerCamelCase__ = "utf-8" lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = True # deprecated lowerCamelCase__ = None # deprecated lowerCamelCase__ = 1_0 << 2_0 # 10MB lowerCamelCase__ = None class lowerCamelCase (datasets.ArrowBasedBuilder ): """simple docstring""" lowerCamelCase__ = JsonConfig def __A ( self : Optional[int] ) -> Optional[int]: if self.config.block_size is not None: logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead" ) SCREAMING_SNAKE_CASE_ = self.config.block_size if self.config.use_threads is not True: logger.warning( "The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore." ) if self.config.newlines_in_values is not None: raise ValueError("The JSON loader parameter `newlines_in_values` is no longer supported" ) return datasets.DatasetInfo(features=self.config.features ) def __A ( self : List[str] , __magic_name__ : str ) -> Tuple: if not self.config.data_files: raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) SCREAMING_SNAKE_CASE_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__magic_name__ , (str, list, tuple) ): SCREAMING_SNAKE_CASE_ = data_files if isinstance(__magic_name__ , __magic_name__ ): SCREAMING_SNAKE_CASE_ = [files] SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(__magic_name__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] SCREAMING_SNAKE_CASE_ = [] for split_name, files in data_files.items(): if isinstance(__magic_name__ , __magic_name__ ): SCREAMING_SNAKE_CASE_ = [files] SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(__magic_name__ ) for file in files] splits.append(datasets.SplitGenerator(name=__magic_name__ , gen_kwargs={"files": files} ) ) return splits def __A ( self : str , __magic_name__ : pa.Table ) -> pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): SCREAMING_SNAKE_CASE_ = self.config.features.arrow_schema.field(__magic_name__ ).type SCREAMING_SNAKE_CASE_ = pa_table.append_column(__magic_name__ , pa.array([None] * len(__magic_name__ ) , type=__magic_name__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example SCREAMING_SNAKE_CASE_ = table_cast(__magic_name__ , self.config.features.arrow_schema ) return pa_table def __A ( self : List[str] , __magic_name__ : List[str] ) -> int: for file_idx, file in enumerate(itertools.chain.from_iterable(__magic_name__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: SCREAMING_SNAKE_CASE_ = json.load(__magic_name__ ) # We keep only the field we are interested in SCREAMING_SNAKE_CASE_ = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__magic_name__ , (list, tuple) ): SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset] ) SCREAMING_SNAKE_CASE_ = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} else: SCREAMING_SNAKE_CASE_ = dataset SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(__magic_name__ ) yield file_idx, self._cast_table(__magic_name__ ) # If the file has one json object per line else: with open(__magic_name__ , "rb" ) as f: SCREAMING_SNAKE_CASE_ = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small SCREAMING_SNAKE_CASE_ = max(self.config.chunksize // 32 , 16 << 10 ) SCREAMING_SNAKE_CASE_ = ( self.config.encoding_errors if self.config.encoding_errors is not None else "strict" ) while True: SCREAMING_SNAKE_CASE_ = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__magic_name__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": SCREAMING_SNAKE_CASE_ = batch.decode(self.config.encoding , errors=__magic_name__ ).encode("utf-8" ) try: while True: try: SCREAMING_SNAKE_CASE_ = paj.read_json( io.BytesIO(__magic_name__ ) , read_options=paj.ReadOptions(block_size=__magic_name__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__magic_name__ , pa.ArrowInvalid ) and "straddling" not in str(__magic_name__ ) or block_size > len(__magic_name__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F'''Batch of {len(__magic_name__ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __magic_name__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: SCREAMING_SNAKE_CASE_ = json.load(__magic_name__ ) except json.JSONDecodeError: logger.error(F'''Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}''' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__magic_name__ , __magic_name__ ): # list is the only sequence type supported in JSON try: SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset] ) SCREAMING_SNAKE_CASE_ = {col: [row.get(__magic_name__ ) for row in dataset] for col in keys} SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(__magic_name__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F'''Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}''' ) raise ValueError(F'''Not able to read records in the JSON file at {file}.''' ) from None yield file_idx, self._cast_table(__magic_name__ ) break else: logger.error(F'''Failed to read file \'{file}\' with error {type(__magic_name__ )}: {e}''' ) raise ValueError( F'''Not able to read records in the JSON file at {file}. ''' F'''You should probably indicate the field of the JSON file containing your records. ''' F'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ''' F'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__magic_name__ ) batch_idx += 1
118
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Dict = None , _lowerCamelCase : Dict = False , ) -> tuple[int, float, str]: '''simple docstring''' __UpperCamelCase : List[str] = cipher_alphabet or [chr(lowerCamelCase_) for i in range(97 , 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) __UpperCamelCase : List[str] = { 'a': 0.0_8_4_9_7, 'b': 0.0_1_4_9_2, 'c': 0.0_2_2_0_2, 'd': 0.0_4_2_5_3, 'e': 0.1_1_1_6_2, 'f': 0.0_2_2_2_8, 'g': 0.0_2_0_1_5, 'h': 0.0_6_0_9_4, 'i': 0.0_7_5_4_6, 'j': 0.0_0_1_5_3, 'k': 0.0_1_2_9_2, 'l': 0.0_4_0_2_5, 'm': 0.0_2_4_0_6, 'n': 0.0_6_7_4_9, 'o': 0.0_7_5_0_7, 'p': 0.0_1_9_2_9, 'q': 0.0_0_0_9_5, 'r': 0.0_7_5_8_7, 's': 0.0_6_3_2_7, 't': 0.0_9_3_5_6, 'u': 0.0_2_7_5_8, 'v': 0.0_0_9_7_8, 'w': 0.0_2_5_6_0, 'x': 0.0_0_1_5_0, 'y': 0.0_1_9_9_4, 'z': 0.0_0_0_7_7, } else: # Custom frequencies dictionary __UpperCamelCase : int = frequencies_dict if not case_sensitive: __UpperCamelCase : str = ciphertext.lower() # Chi squared statistic values __UpperCamelCase : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(lowerCamelCase_)): __UpperCamelCase : Any = '' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet __UpperCamelCase : List[str] = (alphabet_letters.index(letter.lower()) - shift) % len( lowerCamelCase_) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter __UpperCamelCase : str = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: __UpperCamelCase : Optional[int] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message __UpperCamelCase : Union[str, Any] = decrypted_with_shift.lower().count(lowerCamelCase_) # Get the excepcted amount of times the letter should appear based # on letter frequencies __UpperCamelCase : str = frequencies[letter] * occurrences # Complete the chi squared statistic formula __UpperCamelCase : List[str] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message __UpperCamelCase : Union[str, Any] = decrypted_with_shift.count(lowerCamelCase_) # Get the excepcted amount of times the letter should appear based # on letter frequencies __UpperCamelCase : Optional[int] = frequencies[letter] * occurrences # Complete the chi squared statistic formula __UpperCamelCase : Dict = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary __UpperCamelCase : Union[str, Any] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(_lowerCamelCase : Optional[int]) -> tuple[float, str]: return chi_squared_statistic_values[key] __UpperCamelCase : int = min( lowerCamelCase_ , key=lowerCamelCase_ , ) # Get all the data from the most likely cipher (key, decoded message) ( __UpperCamelCase ) : str = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
368
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) lowercase : Optional[Any] = pytest.mark.integration @pytest.mark.parametrize("path" , ["paws", "csv"]) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict , _lowerCamelCase : Tuple) -> Optional[Any]: '''simple docstring''' inspect_dataset(_lowerCamelCase , _lowerCamelCase) __UpperCamelCase : int = path + ".py" assert script_name in os.listdir(_lowerCamelCase) assert "__pycache__" not in os.listdir(_lowerCamelCase) @pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning") @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning") @pytest.mark.parametrize("path" , ["accuracy"]) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int] , _lowerCamelCase : str) -> Optional[Any]: '''simple docstring''' inspect_metric(_lowerCamelCase , _lowerCamelCase) __UpperCamelCase : Dict = path + ".py" assert script_name in os.listdir(_lowerCamelCase) assert "__pycache__" not in os.listdir(_lowerCamelCase) @pytest.mark.parametrize( "path, config_name, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] , _lowerCamelCase : Any , _lowerCamelCase : Any) -> List[str]: '''simple docstring''' __UpperCamelCase : Optional[int] = get_dataset_config_info(_lowerCamelCase , config_name=_lowerCamelCase) assert info.config_name == config_name assert list(info.splits.keys()) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : str , _lowerCamelCase : List[Any] , _lowerCamelCase : int) -> List[str]: '''simple docstring''' with pytest.raises(_lowerCamelCase): get_dataset_config_info(_lowerCamelCase , config_name=_lowerCamelCase) @pytest.mark.parametrize( "path, expected" , [ ("squad", "plain_text"), ("acronym_identification", "default"), ("lhoestq/squad", "plain_text"), ("lhoestq/test", "default"), ("lhoestq/demo1", "lhoestq--demo1"), ("dalle-mini/wit", "dalle-mini--wit"), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict , _lowerCamelCase : Tuple) -> Optional[Any]: '''simple docstring''' __UpperCamelCase : Optional[int] = get_dataset_config_names(_lowerCamelCase) assert expected in config_names @pytest.mark.parametrize( "path, expected_configs, expected_splits_in_first_config" , [ ("squad", ["plain_text"], ["train", "validation"]), ("dalle-mini/wit", ["dalle-mini--wit"], ["train"]), ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int , _lowerCamelCase : Optional[int] , _lowerCamelCase : int) -> Tuple: '''simple docstring''' __UpperCamelCase : List[Any] = get_dataset_infos(_lowerCamelCase) assert list(infos.keys()) == expected_configs __UpperCamelCase : int = expected_configs[0] assert expected_config in infos __UpperCamelCase : Dict = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys()) == expected_splits_in_first_config @pytest.mark.parametrize( "path, expected_config, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] , _lowerCamelCase : Dict , _lowerCamelCase : str) -> str: '''simple docstring''' __UpperCamelCase : Optional[Any] = get_dataset_infos(_lowerCamelCase) assert expected_config in infos __UpperCamelCase : Optional[Any] = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys()) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple , _lowerCamelCase : Optional[int] , _lowerCamelCase : Tuple) -> Dict: '''simple docstring''' with pytest.raises(_lowerCamelCase): get_dataset_split_names(_lowerCamelCase , config_name=_lowerCamelCase)
151
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=7 ,__UpperCAmelCase=3 ,__UpperCAmelCase=30 ,__UpperCAmelCase=400 ,__UpperCAmelCase=True ,__UpperCAmelCase=None ,__UpperCAmelCase=True ,__UpperCAmelCase=[0.5, 0.5, 0.5] ,__UpperCAmelCase=[0.5, 0.5, 0.5] ,__UpperCAmelCase=True ,__UpperCAmelCase=1 / 255 ,__UpperCAmelCase=True ,) -> List[Any]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCAmelCase__ : Any = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} lowerCAmelCase__ : Dict = parent lowerCAmelCase__ : Dict = batch_size lowerCAmelCase__ : List[Any] = num_channels lowerCAmelCase__ : Dict = min_resolution lowerCAmelCase__ : Optional[int] = max_resolution lowerCAmelCase__ : List[str] = do_resize lowerCAmelCase__ : Union[str, Any] = size lowerCAmelCase__ : List[str] = do_normalize lowerCAmelCase__ : Union[str, Any] = image_mean lowerCAmelCase__ : Optional[int] = image_std lowerCAmelCase__ : List[str] = do_rescale lowerCAmelCase__ : Dict = rescale_factor lowerCAmelCase__ : Any = do_pad def UpperCAmelCase_ ( self ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase=False ) -> List[str]: if not batched: lowerCAmelCase__ : int = image_inputs[0] if isinstance(__UpperCAmelCase ,Image.Image ): lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = image.size else: lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = image.shape[1], image.shape[2] if w < h: lowerCAmelCase__ : Optional[int] = int(self.size["""shortest_edge"""] * h / w ) lowerCAmelCase__ : Union[str, Any] = self.size["""shortest_edge"""] elif w > h: lowerCAmelCase__ : List[str] = self.size["""shortest_edge"""] lowerCAmelCase__ : Dict = int(self.size["""shortest_edge"""] * w / h ) else: lowerCAmelCase__ : Dict = self.size["""shortest_edge"""] lowerCAmelCase__ : Tuple = self.size["""shortest_edge"""] else: lowerCAmelCase__ : Dict = [] for image in image_inputs: lowerCAmelCase__ , lowerCAmelCase__ : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase__ : Optional[int] = max(__UpperCAmelCase ,key=lambda __UpperCAmelCase : item[0] )[0] lowerCAmelCase__ : Tuple = max(__UpperCAmelCase ,key=lambda __UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase_( lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' __lowercase : List[Any] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ) -> int: lowerCAmelCase__ : Union[str, Any] = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase ,"""image_mean""" ) ) self.assertTrue(hasattr(__UpperCAmelCase ,"""image_std""" ) ) self.assertTrue(hasattr(__UpperCAmelCase ,"""do_normalize""" ) ) self.assertTrue(hasattr(__UpperCAmelCase ,"""do_resize""" ) ) self.assertTrue(hasattr(__UpperCAmelCase ,"""size""" ) ) def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad ,__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,max_size=84 ,pad_and_return_pixel_mask=__UpperCAmelCase ) self.assertEqual(image_processor.size ,{"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad ,__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Dict: pass def UpperCAmelCase_ ( self ) -> Optional[int]: # Initialize image_processing lowerCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase ,Image.Image ) # Test not batched input lowerCAmelCase__ : str = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ : Any = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = self.image_processor_tester.get_expected_values(__UpperCAmelCase ,batched=__UpperCAmelCase ) lowerCAmelCase__ : List[Any] = image_processing(__UpperCAmelCase ,return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def UpperCAmelCase_ ( self ) -> Optional[int]: # Initialize image_processing lowerCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ : int = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__UpperCAmelCase ,numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase ,np.ndarray ) # Test not batched input lowerCAmelCase__ : List[Any] = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched lowerCAmelCase__ : Union[str, Any] = image_processing(__UpperCAmelCase ,return_tensors="""pt""" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ : List[str] = self.image_processor_tester.get_expected_values(__UpperCAmelCase ,batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def UpperCAmelCase_ ( self ) -> int: # Initialize image_processing lowerCAmelCase__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__UpperCAmelCase ,torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase ,torch.Tensor ) # Test not batched input lowerCAmelCase__ : Dict = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched lowerCAmelCase__ : Union[str, Any] = image_processing(__UpperCAmelCase ,return_tensors="""pt""" ).pixel_values lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = self.image_processor_tester.get_expected_values(__UpperCAmelCase ,batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def UpperCAmelCase_ ( self ) -> Tuple: # Initialize image_processings lowerCAmelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) lowerCAmelCase__ : Dict = self.image_processing_class(do_resize=__UpperCAmelCase ,do_normalize=__UpperCAmelCase ,do_rescale=__UpperCAmelCase ) # create random PyTorch tensors lowerCAmelCase__ : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__UpperCAmelCase ,torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase ,torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors lowerCAmelCase__ : List[Any] = image_processing_a.pad(__UpperCAmelCase ,return_tensors="""pt""" ) lowerCAmelCase__ : List[Any] = image_processing_a(__UpperCAmelCase ,return_tensors="""pt""" ) self.assertTrue( torch.allclose(encoded_images_with_method["""pixel_values"""] ,encoded_images["""pixel_values"""] ,atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self ) -> Any: # prepare image and target lowerCAmelCase__ : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" ,"""r""" ) as f: lowerCAmelCase__ : Optional[Any] = json.loads(f.read() ) lowerCAmelCase__ : Union[str, Any] = {"""image_id""": 3_9769, """annotations""": target} # encode them lowerCAmelCase__ : Dict = YolosImageProcessor.from_pretrained("""hustvl/yolos-small""" ) lowerCAmelCase__ : Dict = image_processing(images=__UpperCAmelCase ,annotations=__UpperCAmelCase ,return_tensors="""pt""" ) # verify pixel values lowerCAmelCase__ : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape ,__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] ,__UpperCAmelCase ,atol=1E-4 ) ) # verify area lowerCAmelCase__ : Union[str, Any] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] ,__UpperCAmelCase ) ) # verify boxes lowerCAmelCase__ : Dict = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape ,__UpperCAmelCase ) lowerCAmelCase__ : Dict = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] ,__UpperCAmelCase ,atol=1E-3 ) ) # verify image_id lowerCAmelCase__ : int = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] ,__UpperCAmelCase ) ) # verify is_crowd lowerCAmelCase__ : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] ,__UpperCAmelCase ) ) # verify class_labels lowerCAmelCase__ : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] ,__UpperCAmelCase ) ) # verify orig_size lowerCAmelCase__ : Any = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] ,__UpperCAmelCase ) ) # verify size lowerCAmelCase__ : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] ,__UpperCAmelCase ) ) @slow def UpperCAmelCase_ ( self ) -> List[Any]: # prepare image, target and masks_path lowerCAmelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" ,"""r""" ) as f: lowerCAmelCase__ : Dict = json.loads(f.read() ) lowerCAmelCase__ : str = {"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target} lowerCAmelCase__ : Any = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them lowerCAmelCase__ : Optional[Any] = YolosImageProcessor(format="""coco_panoptic""" ) lowerCAmelCase__ : Optional[Any] = image_processing(images=__UpperCAmelCase ,annotations=__UpperCAmelCase ,masks_path=__UpperCAmelCase ,return_tensors="""pt""" ) # verify pixel values lowerCAmelCase__ : Optional[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape ,__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] ,__UpperCAmelCase ,atol=1E-4 ) ) # verify area lowerCAmelCase__ : str = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] ,__UpperCAmelCase ) ) # verify boxes lowerCAmelCase__ : int = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape ,__UpperCAmelCase ) lowerCAmelCase__ : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] ,__UpperCAmelCase ,atol=1E-3 ) ) # verify image_id lowerCAmelCase__ : Optional[Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] ,__UpperCAmelCase ) ) # verify is_crowd lowerCAmelCase__ : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] ,__UpperCAmelCase ) ) # verify class_labels lowerCAmelCase__ : Union[str, Any] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] ,__UpperCAmelCase ) ) # verify masks lowerCAmelCase__ : int = 82_2873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() ,__UpperCAmelCase ) # verify orig_size lowerCAmelCase__ : Union[str, Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] ,__UpperCAmelCase ) ) # verify size lowerCAmelCase__ : List[str] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] ,__UpperCAmelCase ) )
37
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
0
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 lowerCamelCase : """simple docstring""" def __init__( self : List[Any], _UpperCAmelCase : List[str], _UpperCAmelCase : Any=2, _UpperCAmelCase : List[str]=3, _UpperCAmelCase : Union[str, Any]=4, _UpperCAmelCase : Union[str, Any]=2, _UpperCAmelCase : int=7, _UpperCAmelCase : Tuple=True, _UpperCAmelCase : int=True, _UpperCAmelCase : List[str]=True, _UpperCAmelCase : List[str]=True, _UpperCAmelCase : Tuple=9_9, _UpperCAmelCase : Any=3_6, _UpperCAmelCase : List[str]=2, _UpperCAmelCase : int=4, _UpperCAmelCase : str=3_7, _UpperCAmelCase : List[str]="gelu", _UpperCAmelCase : Optional[int]=0.1, _UpperCAmelCase : str=0.1, _UpperCAmelCase : Optional[int]=5_1_2, _UpperCAmelCase : Optional[Any]=1_6, _UpperCAmelCase : int=2, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Optional[int]=6, _UpperCAmelCase : List[Any]=6, _UpperCAmelCase : Any=3, _UpperCAmelCase : List[str]=4, _UpperCAmelCase : Tuple=None, _UpperCAmelCase : str=1_0_0_0, ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : int = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : List[Any] = patch_size SCREAMING_SNAKE_CASE__ : List[Any] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = coordinate_size SCREAMING_SNAKE_CASE__ : Tuple = shape_size SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : List[str] = num_choices SCREAMING_SNAKE_CASE__ : Optional[Any] = scope SCREAMING_SNAKE_CASE__ : Any = 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__ : str = text_seq_length SCREAMING_SNAKE_CASE__ : Dict = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE__ : List[str] = self.text_seq_length + self.image_seq_length def A_ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.text_seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length, 4], self.range_bbox ) SCREAMING_SNAKE_CASE__ : List[Any] = 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[Any] = bbox[i, j, 3] SCREAMING_SNAKE_CASE__ : Optional[Any] = bbox[i, j, 1] SCREAMING_SNAKE_CASE__ : Tuple = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE__ : Tuple = bbox[i, j, 2] SCREAMING_SNAKE_CASE__ : str = bbox[i, j, 0] SCREAMING_SNAKE_CASE__ : Dict = tmp_coordinate SCREAMING_SNAKE_CASE__ : Optional[int] = tf.constant(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Dict = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = 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__ : int = None SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.text_seq_length], self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = 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 A_ ( self : Tuple, _UpperCAmelCase : str, _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Any, _UpperCAmelCase : List[Any], _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFLayoutLMvaModel(config=_UpperCAmelCase ) # text + image SCREAMING_SNAKE_CASE__ : str = model(_UpperCAmelCase, pixel_values=_UpperCAmelCase, training=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = model( _UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, attention_mask=_UpperCAmelCase, token_type_ids=_UpperCAmelCase, training=_UpperCAmelCase, ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, training=_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase, training=_UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE__ : Union[str, Any] = model({"pixel_values": pixel_values}, training=_UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.image_seq_length, self.hidden_size) ) def A_ ( self : List[Any], _UpperCAmelCase : List[Any], _UpperCAmelCase : int, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : Dict, _UpperCAmelCase : List[str], _UpperCAmelCase : Dict, _UpperCAmelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.num_labels SCREAMING_SNAKE_CASE__ : List[str] = TFLayoutLMvaForSequenceClassification(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model( _UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, attention_mask=_UpperCAmelCase, token_type_ids=_UpperCAmelCase, labels=_UpperCAmelCase, training=_UpperCAmelCase, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def A_ ( self : List[Any], _UpperCAmelCase : str, _UpperCAmelCase : int, _UpperCAmelCase : str, _UpperCAmelCase : Any, _UpperCAmelCase : List[str], _UpperCAmelCase : List[str], _UpperCAmelCase : Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.num_labels SCREAMING_SNAKE_CASE__ : Dict = TFLayoutLMvaForTokenClassification(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = model( _UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, attention_mask=_UpperCAmelCase, token_type_ids=_UpperCAmelCase, labels=_UpperCAmelCase, training=_UpperCAmelCase, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.text_seq_length, self.num_labels) ) def A_ ( self : Dict, _UpperCAmelCase : Optional[int], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : Dict, _UpperCAmelCase : Union[str, Any], _UpperCAmelCase : int, _UpperCAmelCase : Any, _UpperCAmelCase : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2 SCREAMING_SNAKE_CASE__ : str = TFLayoutLMvaForQuestionAnswering(config=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = model( _UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, attention_mask=_UpperCAmelCase, token_type_ids=_UpperCAmelCase, start_positions=_UpperCAmelCase, end_positions=_UpperCAmelCase, training=_UpperCAmelCase, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def A_ ( self : List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() (SCREAMING_SNAKE_CASE__) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = { "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 lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase_ = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Optional[Any], _UpperCAmelCase : Tuple, _UpperCAmelCase : Any, _UpperCAmelCase : Dict, _UpperCAmelCase : str, _UpperCAmelCase : Optional[int] ) -> List[str]: """simple docstring""" return True def A_ ( self : Optional[int], _UpperCAmelCase : Optional[int], _UpperCAmelCase : str, _UpperCAmelCase : Dict=False ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = copy.deepcopy(_UpperCAmelCase ) if model_class in get_values(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = { k: tf.tile(tf.expand_dims(_UpperCAmelCase, 1 ), (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(_UpperCAmelCase, tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = tf.ones(self.model_tester.batch_size, dtype=tf.intaa ) elif model_class in get_values(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = tf.zeros(self.model_tester.batch_size, dtype=tf.intaa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.zeros(self.model_tester.batch_size, dtype=tf.intaa ) elif model_class in get_values(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : str = tf.zeros(self.model_tester.batch_size, dtype=tf.intaa ) elif model_class in get_values(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length), dtype=tf.intaa ) return inputs_dict def A_ ( self : Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self, config_class=_UpperCAmelCase, hidden_size=3_7 ) def A_ ( self : Optional[int] ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A_ ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(_UpperCAmelCase ) if getattr(_UpperCAmelCase, "hf_compute_loss", _UpperCAmelCase ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_for_class(inputs_dict.copy(), _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys(), reverse=_UpperCAmelCase )[0] ] SCREAMING_SNAKE_CASE__ : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(inputs_dict.copy(), _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE__ : Dict = model(_UpperCAmelCase, **_UpperCAmelCase )[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(), _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = 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__ : Any = -1_0_0 SCREAMING_SNAKE_CASE__ : Dict = tf.convert_to_tensor(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = model(_UpperCAmelCase, **_UpperCAmelCase )[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(), _UpperCAmelCase, return_labels=_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_UpperCAmelCase )[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__ : int = self._prepare_for_class(inputs_dict.copy(), _UpperCAmelCase, return_labels=_UpperCAmelCase ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE__ : List[Any] = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE__ : Dict = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE__ : Tuple = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE__ : str = signature_names.index(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = label_key SCREAMING_SNAKE_CASE__ : str = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE__ : Any = [] 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__ : int = prepared_for_class[value] SCREAMING_SNAKE_CASE__ : List[Any] = tuple(_UpperCAmelCase ) # Send to model SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def A_ ( self : Dict ) -> int: """simple docstring""" ( SCREAMING_SNAKE_CASE__ ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : List[Any] ) -> int: """simple docstring""" ( SCREAMING_SNAKE_CASE__ ) : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : Optional[int] = type self.model_tester.create_and_check_model(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Dict ) -> Optional[Any]: """simple docstring""" ( SCREAMING_SNAKE_CASE__ ) : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Dict ) -> str: """simple docstring""" ( SCREAMING_SNAKE_CASE__ ) : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) def A_ ( self : Any ) -> int: """simple docstring""" ( SCREAMING_SNAKE_CASE__ ) : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) @slow def A_ ( self : Optional[int] ) -> int: """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFLayoutLMvaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def _a ( ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" @cached_property def A_ ( self : Tuple ) -> List[Any]: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=_UpperCAmelCase ) if is_vision_available() else None @slow def A_ ( self : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Dict = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=_UpperCAmelCase, return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE__ : int = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE__ : int = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ), axis=0 ) # forward pass SCREAMING_SNAKE_CASE__ : Dict = model(input_ids=_UpperCAmelCase, bbox=_UpperCAmelCase, pixel_values=_UpperCAmelCase, training=_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = (1, 1_9_9, 7_6_8) self.assertEqual(outputs.last_hidden_state.shape, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[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], _UpperCAmelCase, atol=1E-4 ) )
359
import requests from bsa import BeautifulSoup def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : dict ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ ).content , "html.parser" ) SCREAMING_SNAKE_CASE__ : str = soup.find("div" , attrs={"class": "gs_ri"} ) SCREAMING_SNAKE_CASE__ : int = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _lowerCamelCase : Any = { '''title''': ( '''Precisely geometry controlled microsupercapacitors for ultrahigh areal ''' '''capacitance, volumetric capacitance, and energy density''' ), '''journal''': '''Chem. Mater.''', '''volume''': 3_0, '''pages''': '''3979-3990''', '''year''': 2_0_1_8, '''hl''': '''en''', } print(get_citation('''https://scholar.google.com/scholar_lookup''', params=params))
191
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase__ : Union[str, Any] = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : """simple docstring""" __UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) __UpperCamelCase : Optional[str] = field( default=a__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCamelCase : Optional[str] = field( default='''NER''' , metadata={'''help''': '''Task type to fine tune in training (e.g. NER, POS, etc)'''} ) __UpperCamelCase : Optional[str] = field( default=a__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCamelCase : bool = field(default=a__ , metadata={'''help''': '''Set this flag to use fast tokenization.'''} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __UpperCamelCase : Optional[str] = field( default=a__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class lowerCAmelCase_ : """simple docstring""" __UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'''} ) __UpperCamelCase : Optional[str] = field( default=a__ , metadata={'''help''': '''Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'''} , ) __UpperCamelCase : int = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) __UpperCamelCase : bool = field( default=a__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowercase_ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' """ --overwrite_output_dir to overcome.""" ) SCREAMING_SNAKE_CASE__ : Any = import_module("""tasks""" ) try: SCREAMING_SNAKE_CASE__ : int = getattr(_snake_case ,model_args.task_type ) SCREAMING_SNAKE_CASE__ : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f'''Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN ,) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" ,training_args.local_rank ,training_args.device ,training_args.n_gpu ,bool(training_args.local_rank != -1 ) ,training_args.fpaa ,) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" ,_snake_case ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task SCREAMING_SNAKE_CASE__ : Dict = token_classification_task.get_labels(data_args.labels ) SCREAMING_SNAKE_CASE__ : Dict[int, str] = dict(enumerate(_snake_case ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_snake_case ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=_snake_case ,idalabel=_snake_case ,labelaid={label: i for i, label in enumerate(_snake_case )} ,cache_dir=model_args.cache_dir ,) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,use_fast=model_args.use_fast ,) SCREAMING_SNAKE_CASE__ : List[str] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=_snake_case ,cache_dir=model_args.cache_dir ,) # Get datasets SCREAMING_SNAKE_CASE__ : Tuple = ( TokenClassificationDataset( token_classification_task=_snake_case ,data_dir=data_args.data_dir ,tokenizer=_snake_case ,labels=_snake_case ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.train ,) if training_args.do_train else None ) SCREAMING_SNAKE_CASE__ : Any = ( TokenClassificationDataset( token_classification_task=_snake_case ,data_dir=data_args.data_dir ,tokenizer=_snake_case ,labels=_snake_case ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.dev ,) if training_args.do_eval else None ) def align_predictions(_snake_case ,_snake_case ) -> Tuple[List[int], List[int]]: SCREAMING_SNAKE_CASE__ : Dict = np.argmax(_snake_case ,axis=2 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = preds.shape SCREAMING_SNAKE_CASE__ : int = [[] for _ in range(_snake_case )] SCREAMING_SNAKE_CASE__ : List[str] = [[] for _ in range(_snake_case )] for i in range(_snake_case ): for j in range(_snake_case ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_snake_case ) -> Dict: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = align_predictions(p.predictions ,p.label_ids ) return { "accuracy_score": accuracy_score(_snake_case ,_snake_case ), "precision": precision_score(_snake_case ,_snake_case ), "recall": recall_score(_snake_case ,_snake_case ), "f1": fa_score(_snake_case ,_snake_case ), } # Data collator SCREAMING_SNAKE_CASE__ : List[Any] = DataCollatorWithPadding(_snake_case ,pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Optional[Any] = Trainer( model=_snake_case ,args=_snake_case ,train_dataset=_snake_case ,eval_dataset=_snake_case ,compute_metrics=_snake_case ,data_collator=_snake_case ,) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE__ : Tuple = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Dict = trainer.evaluate() SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(training_args.output_dir ,"""eval_results.txt""" ) if trainer.is_world_process_zero(): with open(_snake_case ,"""w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" ,_snake_case ,_snake_case ) writer.write("""%s = %s\n""" % (key, value) ) results.update(_snake_case ) # Predict if training_args.do_predict: SCREAMING_SNAKE_CASE__ : List[str] = TokenClassificationDataset( token_classification_task=_snake_case ,data_dir=data_args.data_dir ,tokenizer=_snake_case ,labels=_snake_case ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.test ,) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = trainer.predict(_snake_case ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = align_predictions(_snake_case ,_snake_case ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(training_args.output_dir ,"""test_results.txt""" ) if trainer.is_world_process_zero(): with open(_snake_case ,"""w""" ) as writer: for key, value in metrics.items(): logger.info(""" %s = %s""" ,_snake_case ,_snake_case ) writer.write("""%s = %s\n""" % (key, value) ) # Save predictions SCREAMING_SNAKE_CASE__ : Dict = os.path.join(training_args.output_dir ,"""test_predictions.txt""" ) if trainer.is_world_process_zero(): with open(_snake_case ,"""w""" ) as writer: with open(os.path.join(data_args.data_dir ,"""test.txt""" ) ,"""r""" ) as f: token_classification_task.write_predictions_to_file(_snake_case ,_snake_case ,_snake_case ) return results def lowercase_ ( _snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
25
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 __A = random.Random() def lowerCamelCase_ ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str]=1.0 , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Optional[int]=None ) -> Optional[Any]: """simple docstring""" if rng is None: __lowerCamelCase = global_rng __lowerCamelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=7 , lowerCamelCase__=400 , lowerCamelCase__=2_000 , lowerCamelCase__=10 , lowerCamelCase__=160 , lowerCamelCase__=8 , lowerCamelCase__=0.0 , lowerCamelCase__=4_000 , lowerCamelCase__=False , lowerCamelCase__=True , ) -> List[str]: '''simple docstring''' __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = min_seq_length __lowerCamelCase = max_seq_length __lowerCamelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCamelCase = padding_value __lowerCamelCase = sampling_rate __lowerCamelCase = return_attention_mask __lowerCamelCase = do_normalize __lowerCamelCase = feature_size __lowerCamelCase = chunk_length __lowerCamelCase = hop_length def lowercase_ ( self ) -> Any: '''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 lowercase_ ( self , lowerCamelCase__=False , lowerCamelCase__=False ) -> Optional[int]: '''simple docstring''' def _flatten(lowerCamelCase__ ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: __lowerCamelCase = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __lowerCamelCase = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowerCamelCase = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = WhisperFeatureExtractor if is_speech_available() else None def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = WhisperFeatureExtractionTester(self ) def lowercase_ ( self ) -> List[str]: '''simple docstring''' __lowerCamelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) __lowerCamelCase = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) __lowerCamelCase = feat_extract_first.to_dict() __lowerCamelCase = feat_extract_second.to_dict() __lowerCamelCase = feat_extract_first.mel_filters __lowerCamelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) def lowercase_ ( self ) -> Dict: '''simple docstring''' __lowerCamelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase = os.path.join(lowerCamelCase__ , 'feat_extract.json' ) feat_extract_first.to_json_file(lowerCamelCase__ ) __lowerCamelCase = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) __lowerCamelCase = feat_extract_first.to_dict() __lowerCamelCase = feat_extract_second.to_dict() __lowerCamelCase = feat_extract_first.mel_filters __lowerCamelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) def lowercase_ ( self ) -> Dict: '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowerCamelCase = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __lowerCamelCase = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test feature size __lowerCamelCase = feature_extractor(lowerCamelCase__ , 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 __lowerCamelCase = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_features __lowerCamelCase = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_features self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1e-3 ) ) # Test batched __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features 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. __lowerCamelCase = [floats_list((1, x) )[0] for x in (800, 800, 800)] __lowerCamelCase = np.asarray(lowerCamelCase__ ) __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1e-3 ) ) # Test truncation required __lowerCamelCase = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __lowerCamelCase = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] __lowerCamelCase = [x[: feature_extractor.n_samples] for x in speech_inputs] __lowerCamelCase = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs_truncated] __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1e-3 ) ) def lowercase_ ( self ) -> List[str]: '''simple docstring''' import torch __lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCamelCase = np.random.rand(100 , 32 ).astype(np.floataa ) __lowerCamelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCamelCase = feature_extractor.pad([{'input_features': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __lowerCamelCase = feature_extractor.pad([{'input_features': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowercase_ ( self , lowerCamelCase__ ) -> List[str]: '''simple docstring''' __lowerCamelCase = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech __lowerCamelCase = ds.sort('id' ).select(range(lowerCamelCase__ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def lowercase_ ( self ) -> Tuple: '''simple docstring''' # fmt: off __lowerCamelCase = torch.tensor( [ 0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51, 0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78, 0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54, -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54 ] ) # fmt: on __lowerCamelCase = self._load_datasamples(1 ) __lowerCamelCase = WhisperFeatureExtractor() __lowerCamelCase = feature_extractor(lowerCamelCase__ , return_tensors='pt' ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , lowerCamelCase__ , atol=1e-4 ) ) def lowercase_ ( self ) -> List[Any]: '''simple docstring''' __lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCamelCase = self._load_datasamples(1 )[0] __lowerCamelCase = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __lowerCamelCase = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=lowerCamelCase__ )[0] self.assertTrue(np.all(np.mean(lowerCamelCase__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCamelCase__ ) - 1 ) < 1e-3 ) )
90
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class _lowercase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase = GPTSwaTokenizer lowercase = False lowercase = True lowercase = False def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase_ : List[Any] = GPTSwaTokenizer(_SCREAMING_SNAKE_CASE , eos_token='<unk>' , bos_token='<unk>' , pad_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : Tuple ) -> Tuple: """simple docstring""" UpperCamelCase_ : Optional[Any] = "This is a test" UpperCamelCase_ : Optional[int] = "This is a test" return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : Tuple = "<s>" UpperCamelCase_ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 2_0_0_0 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2_0_0_0 ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Tuple: """simple docstring""" UpperCamelCase_ : List[str] = GPTSwaTokenizer(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : Union[str, Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [4_6_5, 2_8_7, 2_6_5, 6_3_1, 8_4_2] ) UpperCamelCase_ : List[str] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) # fmt: off self.assertListEqual( _SCREAMING_SNAKE_CASE , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] , ) # fmt: on UpperCamelCase_ : int = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) self.assertListEqual( _SCREAMING_SNAKE_CASE , [2_6_2, 2_7_2, 1_5_2_5, 2_8_6, 2_7_1, 2_6_8, 6_0, 9_1_6, 6_3_3, 6_3_3, 6_3_3, 2_5_9, 2_6_6, 3_0_1, 2_8_7, 3_8_4, 3_6_7, 2_6_3, 1_9_8, 1_7_2, 2_6_0] , ) UpperCamelCase_ : List[Any] = tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ) # fmt: off self.assertListEqual( _SCREAMING_SNAKE_CASE , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] ) # fmt: on def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ : Dict = GPTSwaTokenizer(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : str = ["This is a test", "I was born in 92000, and this is falsé."] UpperCamelCase_ : Tuple = [ [4_6_5, 2_8_7, 2_6_5, 6_3_1, 8_4_2], [2_6_2, 2_7_2, 1_5_2_5, 2_8_6, 2_7_1, 2_6_8, 6_0, 9_1_6, 6_3_3, 6_3_3, 6_3_3, 2_5_9, 2_6_6, 3_0_1, 2_8_7, 3_8_4, 3_6_7, 2_6_3, 1_9_8, 1_7_2, 2_6_0], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertListEqual(tokenizer.encode_fast(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Test that decode_fast returns the input text for text, token_ids in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertEqual(tokenizer.decode_fast(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase_ : Union[str, Any] = [ "<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')", "Hey there, how are you doing this fine day?", "This is a text with a trailing spaces followed by a dot .", "Häj sväjs lillebrör! =)", "Det är inget fel på Mr. Cool", ] # fmt: off UpperCamelCase_ : Union[str, Any] = {"input_ids": [[6_3_4_2_3, 5, 6_8_1_1, 1_4_9_5_4, 2_8_2, 8_1_6, 3_8_2_1, 6_3_4_6_6, 6_3_4_2_5, 6_3_4_6_2, 1_8, 6_3_9_7_8, 6_7_8, 3_0_1, 1_3_2_0, 6_3_4_2_3, 6_3_4_5_5, 6_3_4_5_8, 1_8, 6_3_9_8_2, 4_2_4_6, 3_9_4_0, 1_9_0_1, 4_7_7_8_9, 5_5_4_7, 1_8_9_9_4], [1_9_6_3_0, 1_1_0_0, 6_3_4_4_6, 1_3_4_2, 6_3_3, 5_4_4, 4_4_8_8, 5_9_3, 5_1_0_2, 2_4_1_6, 6_3_4_9_5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_6_5_2, 4_2_8, 2_6_8, 1_9_3_6, 5_1_5, 2_6_8, 5_8_5_9_3, 2_2_4_1_3, 9_1_0_6, 5_4_6, 2_6_8, 3_3_2_1_3, 6_3_9_7_9, 6_9_8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5_1_3_0, 6_3_4_5_0, 9_2_4, 6_3_4_4_9, 2_2_4_9, 4_0_6_2, 1_5_5_8, 3_1_8, 6_3_5_0_4, 2_1_4_9_8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_0_9, 3_7_7, 2_8_2_7, 2_5_5_9, 3_3_2, 6_5_7_5, 6_3_4_4_3, 2_6_8_0_1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='AI-Sweden/gpt-sw3-126m' , sequences=_SCREAMING_SNAKE_CASE , )
364
import math import flax.linen as nn import jax.numpy as jnp def __lowercase ( lowerCamelCase : jnp.ndarray , lowerCamelCase : int , lowerCamelCase : float = 1 , lowerCamelCase : float = 1 , lowerCamelCase : float = 1.0e4 , lowerCamelCase : bool = False , lowerCamelCase : float = 1.0 , ): assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"Embedding dimension {embedding_dim} should be even" UpperCamelCase_ : Dict = float(embedding_dim // 2 ) UpperCamelCase_ : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) UpperCamelCase_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(lowerCamelCase , dtype=jnp.floataa ) * -log_timescale_increment ) UpperCamelCase_ : int = jnp.expand_dims(lowerCamelCase , 1 ) * jnp.expand_dims(lowerCamelCase , 0 ) # scale embeddings UpperCamelCase_ : Tuple = scale * emb if flip_sin_to_cos: UpperCamelCase_ : Tuple = jnp.concatenate([jnp.cos(lowerCamelCase ), jnp.sin(lowerCamelCase )] , axis=1 ) else: UpperCamelCase_ : Optional[int] = jnp.concatenate([jnp.sin(lowerCamelCase ), jnp.cos(lowerCamelCase )] , axis=1 ) UpperCamelCase_ : Optional[Any] = jnp.reshape(lowerCamelCase , [jnp.shape(lowerCamelCase )[0], embedding_dim] ) return signal class _lowercase ( nn.Module ): lowercase = 3_2 lowercase = jnp.floataa @nn.compact def __call__( self : str , snake_case : Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(snake_case ) UpperCamelCase_ : int = nn.silu(snake_case ) UpperCamelCase_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(snake_case ) return temb class _lowercase ( nn.Module ): lowercase = 3_2 lowercase = False lowercase = 1 @nn.compact def __call__( self : int , snake_case : Any ) -> str: """simple docstring""" return get_sinusoidal_embeddings( snake_case , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
50
0
from collections import Counter from timeit import timeit def lowerCamelCase__ ( _a = "" , ): return sum(c % 2 for c in Counter(input_str.replace(" " , "").lower()).values()) < 2 def lowerCamelCase__ ( _a = ""): if len(_a) == 0: return True SCREAMING_SNAKE_CASE : str = input_str.replace(" " , "").lower() # character_freq_dict: Stores the frequency of every character in the input string SCREAMING_SNAKE_CASE : dict[str, int] = {} for character in lower_case_input_str: SCREAMING_SNAKE_CASE : Dict = character_freq_dict.get(_a , 0) + 1 SCREAMING_SNAKE_CASE : List[Any] = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def lowerCamelCase__ ( _a = ""): print("\nFor string = " , _a , ":") print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(_a) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(_a) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": a_ = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) a_ = can_string_be_rearranged_as_palindrome_counter(check_str) print(F'''{check_str} can {"" if status else "not "}be rearranged as a palindrome''')
76
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __magic_name__ ( __lowerCAmelCase): def __init__( self : Optional[Any] , lowerCamelCase__ : Optional[NestedDataStructureLike[PathLike]] = None , lowerCamelCase__ : Optional[NamedSplit] = None , lowerCamelCase__ : Optional[Features] = None , lowerCamelCase__ : str = None , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = False , lowerCamelCase__ : Optional[int] = None , **lowerCamelCase__ : int , ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : int = path_or_paths UpperCamelCase__ : List[Any] = split if split or isinstance(lowerCamelCase__ , lowerCamelCase__ ) else '''train''' UpperCamelCase__ : Optional[Any] = features UpperCamelCase__ : List[Any] = cache_dir UpperCamelCase__ : Optional[int] = keep_in_memory UpperCamelCase__ : int = streaming UpperCamelCase__ : Union[str, Any] = num_proc UpperCamelCase__ : List[Any] = kwargs @abstractmethod def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: '''simple docstring''' pass class __magic_name__ ( __lowerCAmelCase): def __init__( self : int , lowerCamelCase__ : Optional[Features] = None , lowerCamelCase__ : str = None , lowerCamelCase__ : bool = False , lowerCamelCase__ : bool = False , lowerCamelCase__ : Optional[int] = None , **lowerCamelCase__ : Union[str, Any] , ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Optional[int] = features UpperCamelCase__ : Optional[int] = cache_dir UpperCamelCase__ : Union[str, Any] = keep_in_memory UpperCamelCase__ : Tuple = streaming UpperCamelCase__ : Optional[Any] = num_proc UpperCamelCase__ : Union[str, Any] = kwargs @abstractmethod def UpperCAmelCase__ ( self : Tuple ) -> Union[Dataset, IterableDataset]: '''simple docstring''' pass
146
0
"""simple docstring""" import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class SCREAMING_SNAKE_CASE__ : def __init__( self : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]=None , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : int=None , lowerCAmelCase_ : Optional[int]="resnet50" , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[Any]=3_2 , lowerCAmelCase_ : str=3 , lowerCAmelCase_ : int=True , lowerCAmelCase_ : str=True , ): """simple docstring""" lowercase_ = parent lowercase_ = out_indices if out_indices is not None else [4] lowercase_ = stage_names lowercase_ = out_features lowercase_ = backbone lowercase_ = batch_size lowercase_ = image_size lowercase_ = num_channels lowercase_ = use_pretrained_backbone lowercase_ = is_training def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowercase_ = self.get_config() return config, pixel_values def _UpperCAmelCase ( self : int): """simple docstring""" return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def _UpperCAmelCase ( self : List[str] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int]): """simple docstring""" lowercase_ = TimmBackbone(config=lowerCAmelCase_) model.to(lowerCAmelCase_) model.eval() with torch.no_grad(): lowercase_ = model(lowerCAmelCase_) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , ) def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = self.prepare_config_and_inputs() lowercase_ , lowercase_ = config_and_inputs lowercase_ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch @require_timm class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowercase__ = (TimmBackbone,) if is_torch_available() else () lowercase__ = {"feature-extraction": TimmBackbone} if is_torch_available() else {} lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = TimmBackboneModelTester(self) lowercase_ = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_) def _UpperCAmelCase ( self : int): """simple docstring""" self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCAmelCase ( self : Any): """simple docstring""" lowercase_ = """resnet18""" lowercase_ = """microsoft/resnet-18""" lowercase_ = AutoBackbone.from_pretrained(lowerCAmelCase_ , use_timm_backbone=lowerCAmelCase_) lowercase_ = AutoBackbone.from_pretrained(lowerCAmelCase_) self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features)) self.assertEqual(len(timm_model.stage_names) , len(transformers_model.stage_names)) self.assertEqual(timm_model.channels , transformers_model.channels) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,)) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names) - 1]) lowercase_ = AutoBackbone.from_pretrained(lowerCAmelCase_ , use_timm_backbone=lowerCAmelCase_ , out_indices=[1, 2, 3]) lowercase_ = AutoBackbone.from_pretrained(lowerCAmelCase_ , out_indices=[1, 2, 3]) self.assertEqual(timm_model.out_indices , transformers_model.out_indices) self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features)) self.assertEqual(timm_model.channels , transformers_model.channels) @unittest.skip("""TimmBackbone doesn't support feed forward chunking""") def _UpperCAmelCase ( self : int): """simple docstring""" pass @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""") def _UpperCAmelCase ( self : List[Any]): """simple docstring""" pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""") def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""") def _UpperCAmelCase ( self : List[Any]): """simple docstring""" pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""") def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""") def _UpperCAmelCase ( self : List[Any]): """simple docstring""" pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""") def _UpperCAmelCase ( self : Union[str, Any]): """simple docstring""" pass @unittest.skip("""model weights aren't tied in TimmBackbone.""") def _UpperCAmelCase ( self : Tuple): """simple docstring""" pass @unittest.skip("""model weights aren't tied in TimmBackbone.""") def _UpperCAmelCase ( self : Tuple): """simple docstring""" pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""") def _UpperCAmelCase ( self : str): """simple docstring""" pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""") def _UpperCAmelCase ( self : Tuple): """simple docstring""" pass @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""") def _UpperCAmelCase ( self : List[Any]): """simple docstring""" pass @unittest.skip("""TimmBackbone doesn't support output_attentions.""") def _UpperCAmelCase ( self : List[str]): """simple docstring""" pass @unittest.skip("""Safetensors is not supported by timm.""") def _UpperCAmelCase ( self : List[str]): """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" pass def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ = model_class(lowerCAmelCase_) lowercase_ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ = [*signature.parameters.keys()] lowercase_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCAmelCase_) def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = True lowercase_ = self.has_attentions # no need to test all models as different heads yield the same functionality lowercase_ = self.all_model_classes[0] lowercase_ = model_class(lowerCAmelCase_) model.to(lowerCAmelCase_) lowercase_ = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_) lowercase_ = model(**lowerCAmelCase_) lowercase_ = outputs[0][-1] # Encoder-/Decoder-only models lowercase_ = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: lowercase_ = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowerCAmelCase_) self.assertIsNotNone(hidden_states.grad) if self.has_attentions: self.assertIsNotNone(attentions.grad) def _UpperCAmelCase ( self : List[Any]): """simple docstring""" lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ = model_class(lowerCAmelCase_) model.to(lowerCAmelCase_) model.eval() lowercase_ = model(**lowerCAmelCase_) self.assertEqual(len(result.feature_maps) , len(config.out_indices)) self.assertEqual(len(model.channels) , len(config.out_indices)) # Check output of last stage is taken if out_features=None, out_indices=None lowercase_ = copy.deepcopy(lowerCAmelCase_) lowercase_ = None lowercase_ = model_class(lowerCAmelCase_) model.to(lowerCAmelCase_) model.eval() lowercase_ = model(**lowerCAmelCase_) self.assertEqual(len(result.feature_maps) , 1) self.assertEqual(len(model.channels) , 1) # Check backbone can be initialized with fresh weights lowercase_ = copy.deepcopy(lowerCAmelCase_) lowercase_ = False lowercase_ = model_class(lowerCAmelCase_) model.to(lowerCAmelCase_) model.eval() lowercase_ = model(**lowerCAmelCase_)
313
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = { "configuration_upernet": ["UperNetConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = [ "UperNetForSemanticSegmentation", "UperNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
313
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : int=1_2 , __UpperCAmelCase : str=7 , __UpperCAmelCase : str=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Tuple=9_9 , __UpperCAmelCase : int=3_2 , __UpperCAmelCase : Optional[int]=3_2 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : List[str]=4 , __UpperCAmelCase : Optional[int]=3_7 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Optional[int]=5_1_2 , __UpperCAmelCase : Optional[int]=0.02 , __UpperCAmelCase : Optional[Any]=0 , __UpperCAmelCase : Optional[int]=None , ) -> str: SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = projection_dim SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = bos_token_id def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: SCREAMING_SNAKE_CASE__ = input_mask.numpy() SCREAMING_SNAKE_CASE__ = input_mask.shape SCREAMING_SNAKE_CASE__ = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(snake_case_ ): SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = self.get_config() return config, input_ids, tf.convert_to_tensor(snake_case_ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ = TFBlipTextModel(config=snake_case_ ) SCREAMING_SNAKE_CASE__ = model(snake_case_ , attention_mask=snake_case_ , training=snake_case_ ) SCREAMING_SNAKE_CASE__ = model(snake_case_ , training=snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class lowerCamelCase (_a ,unittest.TestCase ): lowerCamelCase__ : int = (TFBlipTextModel,) if is_tf_available() else () lowerCamelCase__ : Any = False lowerCamelCase__ : Optional[int] = False lowerCamelCase__ : str = False def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: SCREAMING_SNAKE_CASE__ = BlipTextModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=snake_case_ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : int ) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: pass def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: pass @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = TFBlipTextModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : List[str]=True ) -> Any: super().test_pt_tf_model_equivalence(allow_missing_keys=snake_case_ )
165
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a_ : def __init__( self , snake_case_ , snake_case_=1_3 , snake_case_=3_0 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=3_2 , snake_case_=5 , snake_case_=4 , snake_case_=3_7 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=1_0 , snake_case_=0.02 , snake_case_=None , ): _lowerCAmelCase : Optional[Any] = parent _lowerCAmelCase : Any = batch_size _lowerCAmelCase : Tuple = image_size _lowerCAmelCase : int = patch_size _lowerCAmelCase : Any = num_channels _lowerCAmelCase : str = is_training _lowerCAmelCase : Any = use_labels _lowerCAmelCase : List[Any] = hidden_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Union[str, Any] = intermediate_size _lowerCAmelCase : Dict = hidden_act _lowerCAmelCase : str = hidden_dropout_prob _lowerCAmelCase : Optional[int] = attention_probs_dropout_prob _lowerCAmelCase : Any = type_sequence_label_size _lowerCAmelCase : str = initializer_range _lowerCAmelCase : Optional[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _lowerCAmelCase : List[Any] = (image_size // patch_size) ** 2 _lowerCAmelCase : Dict = num_patches + 1 def __UpperCamelCase ( self ): _lowerCAmelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : List[str] = None if self.use_labels: _lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Optional[Any] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , snake_case_ , snake_case_ , snake_case_ ): _lowerCAmelCase : List[Any] = ViTMSNModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() _lowerCAmelCase : Optional[Any] = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , snake_case_ , snake_case_ , snake_case_ ): _lowerCAmelCase : Tuple = self.type_sequence_label_size _lowerCAmelCase : int = ViTMSNForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() _lowerCAmelCase : Optional[int] = model(snake_case_ , labels=snake_case_ ) print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" ) print("""Labels: {labels}""" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _lowerCAmelCase : int = 1 _lowerCAmelCase : List[str] = ViTMSNForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() _lowerCAmelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : Optional[int] = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCamelCase ( self ): _lowerCAmelCase : List[str] = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[Any] = config_and_inputs _lowerCAmelCase : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ (_a , _a , unittest.TestCase ): __lowerCAmelCase : Tuple = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () __lowerCAmelCase : Optional[int] = ( {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification} if is_torch_available() else {} ) __lowerCAmelCase : Dict = False __lowerCAmelCase : Optional[Any] = False __lowerCAmelCase : List[str] = False __lowerCAmelCase : Any = False def __UpperCamelCase ( self ): _lowerCAmelCase : Tuple = ViTMSNModelTester(self ) _lowerCAmelCase : int = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMSN does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): _lowerCAmelCase , _lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : List[str] = model_class(snake_case_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCAmelCase : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case_ , nn.Linear ) ) def __UpperCamelCase ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Optional[int] = model_class(snake_case_ ) _lowerCAmelCase : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : Optional[Any] = [*signature.parameters.keys()] _lowerCAmelCase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def __UpperCamelCase ( self ): for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Optional[int] = ViTMSNModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def _UpperCAmelCase ( ) -> Tuple: _lowerCAmelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ (unittest.TestCase ): @cached_property def __UpperCamelCase ( self ): return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None @slow def __UpperCamelCase ( self ): torch.manual_seed(2 ) _lowerCAmelCase : Dict = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(snake_case_ ) _lowerCAmelCase : Dict = self.default_image_processor _lowerCAmelCase : Any = prepare_img() _lowerCAmelCase : List[str] = image_processor(images=snake_case_ , return_tensors="""pt""" ).to(snake_case_ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Dict = model(**snake_case_ ) # verify the logits _lowerCAmelCase : Dict = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , snake_case_ ) _lowerCAmelCase : Tuple = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1E-4 ) )
309
0
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : dict ): """simple docstring""" _snake_case : Optional[int] = set() # edges = list of graph's edges _snake_case : Any = get_edges(snake_case__ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: _snake_case , _snake_case : Optional[int] = edges.pop() chosen_vertices.add(snake_case__ ) chosen_vertices.add(snake_case__ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(snake_case__ ) return chosen_vertices def UpperCAmelCase__ (snake_case__ : dict ): """simple docstring""" _snake_case : Any = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
132
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowercase( __a ): '''simple docstring''' def __init__( self: Optional[int], a_: str, a_: Optional[Any] ): '''simple docstring''' super().__init__() self.register_modules(unet=a_, scheduler=a_ ) @torch.no_grad() def __call__( self: Any, a_: int = 1, a_: int = 100, a_: Optional[Union[torch.Generator, List[torch.Generator]]] = None, a_: Optional[float] = None, a_: bool = True, ): '''simple docstring''' if audio_length_in_s is None: _snake_case : Dict = self.unet.config.sample_size / self.unet.config.sample_rate _snake_case : Optional[int] = audio_length_in_s * self.unet.config.sample_rate _snake_case : int = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"{audio_length_in_s} is too small. Make sure it's bigger or equal to" f" {3 * down_scale_factor / self.unet.config.sample_rate}." ) _snake_case : Union[str, Any] = int(a_ ) if sample_size % down_scale_factor != 0: _snake_case : Optional[Any] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled" f" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising" """ process.""" ) _snake_case : str = int(a_ ) _snake_case : int = next(iter(self.unet.parameters() ) ).dtype _snake_case : Optional[Any] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(a_, a_ ) and len(a_ ) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(a_ )}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) _snake_case : Optional[Any] = randn_tensor(a_, generator=a_, device=self.device, dtype=a_ ) # set step values self.scheduler.set_timesteps(a_, device=audio.device ) _snake_case : Optional[int] = self.scheduler.timesteps.to(a_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _snake_case : str = self.unet(a_, a_ ).sample # 2. compute previous image: x_t -> t_t-1 _snake_case : Optional[Any] = self.scheduler.step(a_, a_, a_ ).prev_sample _snake_case : Tuple = audio.clamp(-1, 1 ).float().cpu().numpy() _snake_case : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=a_ )
132
1
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class UpperCamelCase__ ( A__ ): """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any=1_3 , SCREAMING_SNAKE_CASE_ : List[str]=7 , SCREAMING_SNAKE_CASE_ : int=True , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Any=9_9 , SCREAMING_SNAKE_CASE_ : Optional[int]=3_2 , SCREAMING_SNAKE_CASE_ : Any=5 , SCREAMING_SNAKE_CASE_ : List[Any]=4 , SCREAMING_SNAKE_CASE_ : Dict=6_4 , SCREAMING_SNAKE_CASE_ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE_ : Tuple=0.1 , SCREAMING_SNAKE_CASE_ : Any=0.1 , SCREAMING_SNAKE_CASE_ : List[Any]=5_1_2 , SCREAMING_SNAKE_CASE_ : Dict=1_6 , SCREAMING_SNAKE_CASE_ : Optional[Any]=2 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE_ : List[str]=3 , SCREAMING_SNAKE_CASE_ : Optional[Any]=4 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None , SCREAMING_SNAKE_CASE_ : Tuple=2 , SCREAMING_SNAKE_CASE_ : List[str]=2 , SCREAMING_SNAKE_CASE_ : str=2 , SCREAMING_SNAKE_CASE_ : Dict=2 , SCREAMING_SNAKE_CASE_ : Optional[Any]=4 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1 , ): lowerCAmelCase_ : List[Any] = parent lowerCAmelCase_ : Optional[int] = batch_size lowerCAmelCase_ : Dict = seq_length lowerCAmelCase_ : Dict = is_training lowerCAmelCase_ : Optional[int] = use_input_mask lowerCAmelCase_ : int = use_token_type_ids lowerCAmelCase_ : Optional[int] = use_labels lowerCAmelCase_ : Tuple = vocab_size lowerCAmelCase_ : Any = hidden_size lowerCAmelCase_ : Union[str, Any] = num_hidden_layers lowerCAmelCase_ : Tuple = num_attention_heads lowerCAmelCase_ : List[Any] = intermediate_size lowerCAmelCase_ : List[str] = hidden_act lowerCAmelCase_ : List[str] = hidden_dropout_prob lowerCAmelCase_ : Optional[int] = attention_probs_dropout_prob lowerCAmelCase_ : str = max_position_embeddings lowerCAmelCase_ : str = type_vocab_size lowerCAmelCase_ : List[str] = type_sequence_label_size lowerCAmelCase_ : Optional[Any] = initializer_range lowerCAmelCase_ : Tuple = num_labels lowerCAmelCase_ : List[Any] = num_choices lowerCAmelCase_ : Dict = scope lowerCAmelCase_ : int = q_groups lowerCAmelCase_ : Tuple = k_groups lowerCAmelCase_ : List[Any] = v_groups lowerCAmelCase_ : Tuple = post_attention_groups lowerCAmelCase_ : int = intermediate_groups lowerCAmelCase_ : List[Any] = output_groups def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowerCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase_ : List[Any] = None if self.use_input_mask: lowerCAmelCase_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase_ : Optional[Any] = None lowerCAmelCase_ : Any = None lowerCAmelCase_ : str = None if self.use_labels: lowerCAmelCase_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase_ : Optional[int] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : str ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): lowerCAmelCase_ : List[Any] = SqueezeBertModel(config=_A ) model.to(_A ) model.eval() lowerCAmelCase_ : Any = model(_A , _A ) lowerCAmelCase_ : List[str] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Dict , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): lowerCAmelCase_ : List[Any] = SqueezeBertForMaskedLM(config=_A ) model.to(_A ) model.eval() lowerCAmelCase_ : List[str] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] ): lowerCAmelCase_ : Union[str, Any] = SqueezeBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() lowerCAmelCase_ : Dict = model( _A , attention_mask=_A , start_positions=_A , end_positions=_A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ): lowerCAmelCase_ : int = self.num_labels lowerCAmelCase_ : List[str] = SqueezeBertForSequenceClassification(_A ) model.to(_A ) model.eval() lowerCAmelCase_ : Dict = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict ): lowerCAmelCase_ : Optional[Any] = self.num_labels lowerCAmelCase_ : Optional[int] = SqueezeBertForTokenClassification(config=_A ) model.to(_A ) model.eval() lowerCAmelCase_ : Optional[int] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] ): lowerCAmelCase_ : List[Any] = self.num_choices lowerCAmelCase_ : Union[str, Any] = SqueezeBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() lowerCAmelCase_ : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase_ : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase_ : Optional[int] = model( _A , attention_mask=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowerCAmelCase_ : Optional[Any] = self.prepare_config_and_inputs() (lowerCAmelCase_) : Dict = config_and_inputs lowerCAmelCase_ : Dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( A__, A__, unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) _SCREAMING_SNAKE_CASE = ( { """feature-extraction""": SqueezeBertModel, """fill-mask""": SqueezeBertForMaskedLM, """question-answering""": SqueezeBertForQuestionAnswering, """text-classification""": SqueezeBertForSequenceClassification, """token-classification""": SqueezeBertForTokenClassification, """zero-shot""": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : int = SqueezeBertModelTester(self ) lowerCAmelCase_ : List[str] = ConfigTester(self , config_class=_A , dim=3_7 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowerCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*_A ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*_A ) def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*_A ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_A ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowerCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*_A ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowerCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_A ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_ : Tuple = SqueezeBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_sentencepiece @require_tokenizers @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : str = SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) lowerCAmelCase_ : Optional[int] = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] ) lowerCAmelCase_ : List[Any] = model(_A )[0] lowerCAmelCase_ : Union[str, Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , _A ) lowerCAmelCase_ : int = torch.tensor([[0.64_01, -0.03_49, -0.60_41]] ) self.assertTrue(torch.allclose(_A , _A , atol=1E-4 ) )
224
from __future__ import annotations from math import pi, sqrt def _snake_case ( lowerCAmelCase : float , lowerCAmelCase : float ): """simple docstring""" if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative" ) elif capacitance <= 0: raise ValueError("Capacitance cannot be 0 or negative" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
18
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { 'huggingface/time-series-transformer-tourism-monthly': ( 'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json' ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class snake_case ( _lowerCamelCase ): a_ : Dict = """time_series_transformer""" a_ : Any = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", """num_hidden_layers""": """encoder_layers""", } def __init__( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "student_t" , __UpperCAmelCase = "nll" , __UpperCAmelCase = 1 , __UpperCAmelCase = [1, 2, 3, 4, 5, 6, 7] , __UpperCAmelCase = "mean" , __UpperCAmelCase = 0 , __UpperCAmelCase = 0 , __UpperCAmelCase = 0 , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 32 , __UpperCAmelCase = 32 , __UpperCAmelCase = 2 , __UpperCAmelCase = 2 , __UpperCAmelCase = 2 , __UpperCAmelCase = 2 , __UpperCAmelCase = True , __UpperCAmelCase = "gelu" , __UpperCAmelCase = 64 , __UpperCAmelCase = 0.1 , __UpperCAmelCase = 0.1 , __UpperCAmelCase = 0.1 , __UpperCAmelCase = 0.1 , __UpperCAmelCase = 0.1 , __UpperCAmelCase = 1_00 , __UpperCAmelCase = 0.02 , __UpperCAmelCase=True , **__UpperCAmelCase , ) ->Optional[Any]: a_ = prediction_length a_ = context_length or prediction_length a_ = distribution_output a_ = loss a_ = input_size a_ = num_time_features a_ = lags_sequence a_ = scaling a_ = num_dynamic_real_features a_ = num_static_real_features a_ = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(__UpperCAmelCase) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`") a_ = cardinality else: a_ = [0] if embedding_dimension and num_static_categorical_features > 0: if len(__UpperCAmelCase) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`") a_ = embedding_dimension else: a_ = [min(50 , (cat + 1) // 2) for cat in self.cardinality] a_ = num_parallel_samples # Transformer architecture configuration a_ = input_size * len(__UpperCAmelCase) + self._number_of_features a_ = d_model a_ = encoder_attention_heads a_ = decoder_attention_heads a_ = encoder_ffn_dim a_ = decoder_ffn_dim a_ = encoder_layers a_ = decoder_layers a_ = dropout a_ = attention_dropout a_ = activation_dropout a_ = encoder_layerdrop a_ = decoder_layerdrop a_ = activation_function a_ = init_std a_ = use_cache super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase) @property def UpperCAmelCase__ ( self) ->List[Any]: return ( sum(self.embedding_dimension) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
353
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self) ->Dict: a_ = inspect.getfile(accelerate.test_utils) a_ = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) a_ = os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) a_ = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def UpperCAmelCase__ ( self) ->Any: print(F'''Found {torch.cuda.device_count()} devices.''') a_ = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy()) @require_multi_gpu def UpperCAmelCase__ ( self) ->str: print(F'''Found {torch.cuda.device_count()} devices.''') a_ = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(F'''Command: {cmd}''') with patch_environment(omp_num_threads=1): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy()) @require_multi_gpu def UpperCAmelCase__ ( self) ->Optional[int]: a_ = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy()) @require_multi_gpu def UpperCAmelCase__ ( self) ->List[Any]: print(F'''Found {torch.cuda.device_count()} devices, using 2 devices only''') a_ = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy()) if __name__ == "__main__": UpperCamelCase_ = Accelerator() UpperCamelCase_ = (accelerator.state.process_index + 2, 10) UpperCamelCase_ = torch.randint(0, 10, shape).to(accelerator.device) UpperCamelCase_ = '' UpperCamelCase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." UpperCamelCase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." UpperCamelCase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
303
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class a_ ( snake_case_ ): __A = 42 class a_ ( snake_case_ , snake_case_ ): @register_to_config def __init__( self : Optional[Any] , lowercase : Union[str, Any] = 65_536 , lowercase : Any = None , lowercase : Optional[Any] = 2 , lowercase : List[str] = 2 , lowercase : str = 0 , lowercase : int = "fourier" , lowercase : Optional[Any] = True , lowercase : Optional[int] = False , lowercase : str = 0.0 , lowercase : Optional[int] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , lowercase : List[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , lowercase : List[str] = "UNetMidBlock1D" , lowercase : Dict = None , lowercase : Optional[Any] = (32, 32, 64) , lowercase : Optional[Any] = None , lowercase : Any = 8 , lowercase : str = 1 , lowercase : Optional[int] = False , ): """simple docstring""" super().__init__() lowercase_ :List[Any] = sample_size # time if time_embedding_type == "fourier": lowercase_ :Union[str, Any] = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=UpperCamelCase__ , log=UpperCamelCase__ , flip_sin_to_cos=UpperCamelCase__ ) lowercase_ :Dict = 2 * block_out_channels[0] elif time_embedding_type == "positional": lowercase_ :List[str] = Timesteps( block_out_channels[0] , flip_sin_to_cos=UpperCamelCase__ , downscale_freq_shift=UpperCamelCase__ ) lowercase_ :int = block_out_channels[0] if use_timestep_embedding: lowercase_ :List[str] = block_out_channels[0] * 4 lowercase_ :List[str] = TimestepEmbedding( in_channels=UpperCamelCase__ , time_embed_dim=UpperCamelCase__ , act_fn=UpperCamelCase__ , out_dim=block_out_channels[0] , ) lowercase_ :Optional[int] = nn.ModuleList([] ) lowercase_ :Dict = None lowercase_ :Tuple = nn.ModuleList([] ) lowercase_ :int = None # down lowercase_ :Any = in_channels for i, down_block_type in enumerate(UpperCamelCase__ ): lowercase_ :Dict = output_channel lowercase_ :int = block_out_channels[i] if i == 0: input_channel += extra_in_channels lowercase_ :Any = i == len(UpperCamelCase__ ) - 1 lowercase_ :Tuple = get_down_block( UpperCamelCase__ , num_layers=UpperCamelCase__ , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(UpperCamelCase__ ) # mid lowercase_ :str = get_mid_block( UpperCamelCase__ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=UpperCamelCase__ , add_downsample=UpperCamelCase__ , ) # up lowercase_ :Optional[int] = list(reversed(UpperCamelCase__ ) ) lowercase_ :int = reversed_block_out_channels[0] if out_block_type is None: lowercase_ :List[Any] = out_channels else: lowercase_ :int = block_out_channels[0] for i, up_block_type in enumerate(UpperCamelCase__ ): lowercase_ :Optional[int] = output_channel lowercase_ :List[Any] = ( reversed_block_out_channels[i + 1] if i < len(UpperCamelCase__ ) - 1 else final_upsample_channels ) lowercase_ :List[str] = i == len(UpperCamelCase__ ) - 1 lowercase_ :Union[str, Any] = get_up_block( UpperCamelCase__ , num_layers=UpperCamelCase__ , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(UpperCamelCase__ ) lowercase_ :Any = output_channel # out lowercase_ :str = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) lowercase_ :Dict = get_out_block( out_block_type=UpperCamelCase__ , num_groups_out=UpperCamelCase__ , embed_dim=block_out_channels[0] , out_channels=UpperCamelCase__ , act_fn=UpperCamelCase__ , fc_dim=block_out_channels[-1] // 4 , ) def lowercase__ ( self : str , lowercase : Tuple , lowercase : Tuple , lowercase : Dict = True , ): """simple docstring""" lowercase_ :Tuple = timestep if not torch.is_tensor(UpperCamelCase__ ): lowercase_ :Tuple = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(UpperCamelCase__ ) and len(timesteps.shape ) == 0: lowercase_ :List[str] = timesteps[None].to(sample.device ) lowercase_ :str = self.time_proj(UpperCamelCase__ ) if self.config.use_timestep_embedding: lowercase_ :Tuple = self.time_mlp(UpperCamelCase__ ) else: lowercase_ :int = timestep_embed[..., None] lowercase_ :Optional[Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) lowercase_ :Optional[int] = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down lowercase_ :List[str] = () for downsample_block in self.down_blocks: lowercase_ :Dict = downsample_block(hidden_states=UpperCamelCase__ , temb=UpperCamelCase__ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: lowercase_ :int = self.mid_block(UpperCamelCase__ , UpperCamelCase__ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): lowercase_ :Any = down_block_res_samples[-1:] lowercase_ :int = down_block_res_samples[:-1] lowercase_ :Optional[int] = upsample_block(UpperCamelCase__ , res_hidden_states_tuple=UpperCamelCase__ , temb=UpperCamelCase__ ) # 5. post-process if self.out_block: lowercase_ :Any = self.out_block(UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (sample,) return UNetaDOutput(sample=UpperCamelCase__ )
223
"""simple docstring""" def __lowerCAmelCase ( lowercase : list[int] ) -> float: """simple docstring""" if not nums: # Makes sure that the list is not empty raise ValueError("List is empty" ) snake_case : List[str] = sum(lowercase ) / len(lowercase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
203
0
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = "▁" lowercase_ = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} lowercase_ = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } lowercase_ = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } lowercase_ = { "ernie-m-base": 5_14, "ernie-m-large": 5_14, } lowercase_ = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): A : List[str] = ["input_ids"] A : Tuple = VOCAB_FILES_NAMES A : List[Any] = PRETRAINED_INIT_CONFIGURATION A : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A : Optional[Any] = RESOURCE_FILES_NAMES def __init__( self : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict=None , _lowerCAmelCase : Dict=False , _lowerCAmelCase : List[Any]="utf8" , _lowerCAmelCase : Optional[Any]="[UNK]" , _lowerCAmelCase : Optional[int]="[SEP]" , _lowerCAmelCase : List[str]="[PAD]" , _lowerCAmelCase : Dict="[CLS]" , _lowerCAmelCase : List[Any]="[MASK]" , _lowerCAmelCase : Optional[Dict[str, Any]] = None , **_lowerCAmelCase : Any , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __snake_case : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , vocab_file=_lowerCAmelCase , encoding=_lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCAmelCase , ) __snake_case : List[Any] = do_lower_case __snake_case : Any = sentencepiece_model_ckpt __snake_case : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCAmelCase ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: __snake_case : int = self.load_vocab(filepath=_lowerCAmelCase ) else: __snake_case : Tuple = {self.sp_model.id_to_piece(_lowerCAmelCase ): id for id in range(self.sp_model.get_piece_size() )} __snake_case : str = {v: k for k, v in self.vocab.items()} def snake_case__ ( self : List[Any] , _lowerCAmelCase : List[Any] ): if text is None: return None __snake_case : List[Any] = self.tokenize(_lowerCAmelCase ) __snake_case : Optional[Any] = """""", [] for i, ch in enumerate(_lowerCAmelCase ): if ch in self.SP_CHAR_MAPPING: __snake_case : Any = self.SP_CHAR_MAPPING.get(_lowerCAmelCase ) else: __snake_case : Dict = unicodedata.normalize("""NFKC""" , _lowerCAmelCase ) if self.is_whitespace(_lowerCAmelCase ): continue normalized_text += ch char_mapping.extend([i] * len(_lowerCAmelCase ) ) __snake_case : str = normalized_text, [], 0 if self.do_lower_case: __snake_case : int = text.lower() for token in split_tokens: if token[:1] == "▁": __snake_case : int = token[1:] __snake_case : Optional[int] = text[offset:].index(_lowerCAmelCase ) + offset __snake_case : int = start + len(_lowerCAmelCase ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) __snake_case : str = end return token_mapping @property def snake_case__ ( self : Tuple ): return len(self.vocab ) def snake_case__ ( self : Dict ): return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : int ): __snake_case : str = self.__dict__.copy() __snake_case : Union[str, Any] = None return state def __setstate__( self : Optional[Any] , _lowerCAmelCase : List[str] ): __snake_case : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __snake_case : Optional[Any] = {} __snake_case : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def snake_case__ ( self : str , _lowerCAmelCase : Optional[int] ): return "".join((self.SP_CHAR_MAPPING.get(_lowerCAmelCase , _lowerCAmelCase ) for c in text) ) def snake_case__ ( self : Optional[Any] , _lowerCAmelCase : str , _lowerCAmelCase : Tuple=False , _lowerCAmelCase : Optional[Any]=64 , _lowerCAmelCase : Optional[int]=0.1 ): if self.sp_model_kwargs.get("""enable_sampling""" ) is True: __snake_case : List[str] = True if self.sp_model_kwargs.get("""alpha""" ) is not None: __snake_case : Dict = self.sp_model_kwargs.get("""alpha""" ) if self.sp_model_kwargs.get("""nbest_size""" ) is not None: __snake_case : List[Any] = self.sp_model_kwargs.get("""nbest_size""" ) if not enable_sampling: __snake_case : str = self.sp_model.EncodeAsPieces(_lowerCAmelCase ) else: __snake_case : Tuple = self.sp_model.SampleEncodeAsPieces(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) __snake_case : Union[str, Any] = [] for pi, piece in enumerate(_lowerCAmelCase ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(_lowerCAmelCase ) and pi != 0: new_pieces.append(_lowerCAmelCase ) continue else: continue __snake_case : Optional[int] = 0 for i, chunk in enumerate(_lowerCAmelCase ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(_lowerCAmelCase ) or self.is_punct(_lowerCAmelCase ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(_lowerCAmelCase ) __snake_case : Tuple = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) __snake_case : List[str] = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) __snake_case : Tuple = i if len(_lowerCAmelCase ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : int ): __snake_case : int = """""".join(_lowerCAmelCase ).replace(_lowerCAmelCase , """ """ ).strip() return out_string def snake_case__ ( self : Dict , _lowerCAmelCase : Tuple ): __snake_case : int = self.convert_ids_to_tokens(_lowerCAmelCase ) __snake_case : Any = """""".join(_lowerCAmelCase ).replace(_lowerCAmelCase , """ """ ).strip() return out_string def snake_case__ ( self : Dict , _lowerCAmelCase : Tuple ): return self.vocab.get(_lowerCAmelCase , self.vocab.get(self.unk_token ) ) def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : Dict ): return self.reverse_vocab.get(_lowerCAmelCase , self.unk_token ) def snake_case__ ( self : Any , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Union[str, Any]=None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __snake_case : Union[str, Any] = [self.cls_token_id] __snake_case : Optional[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def snake_case__ ( self : List[str] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any]=None ): if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def snake_case__ ( self : Optional[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[Any]=False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_lowerCAmelCase )) + [1, 1] + ([0] * len(_lowerCAmelCase )) + [1] return [1] + ([0] * len(_lowerCAmelCase )) + [1] def snake_case__ ( self : Optional[int] , _lowerCAmelCase : List[int] , _lowerCAmelCase : Optional[List[int]] = None ): # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(_lowerCAmelCase ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(_lowerCAmelCase ) + 1) + [1] * (len(_lowerCAmelCase ) + 3) def snake_case__ ( self : Tuple , _lowerCAmelCase : List[str] ): if "\u4e00" <= char <= "\u9fff": return True return False def snake_case__ ( self : List[str] , _lowerCAmelCase : Any ): if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def snake_case__ ( self : int , _lowerCAmelCase : List[Any] ): if char in ",;:.?!~,;:。?!《》【】": return True return False def snake_case__ ( self : str , _lowerCAmelCase : Optional[Any] ): if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(_lowerCAmelCase ) == 1: __snake_case : Dict = unicodedata.category(_lowerCAmelCase ) if cat == "Zs": return True return False def snake_case__ ( self : str , _lowerCAmelCase : List[Any] ): __snake_case : Dict = {} with io.open(_lowerCAmelCase , """r""" , encoding="""utf-8""" ) as f: for index, line in enumerate(_lowerCAmelCase ): __snake_case : Tuple = line.rstrip("""\n""" ) __snake_case : List[str] = int(_lowerCAmelCase ) return token_to_idx def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : str , _lowerCAmelCase : Optional[str] = None ): __snake_case : Optional[int] = 0 if os.path.isdir(_lowerCAmelCase ): __snake_case : int = os.path.join( _lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) else: __snake_case : Optional[Any] = (filename_prefix + """-""" if filename_prefix else """""") + save_directory with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda _lowerCAmelCase : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' """ Please check that the vocabulary is not corrupted!""" ) __snake_case : Union[str, Any] = token_index writer.write(token + """\n""" ) index += 1 __snake_case : List[Any] = os.path.join(_lowerCAmelCase , """sentencepiece.bpe.model""" ) with open(_lowerCAmelCase , """wb""" ) as fi: __snake_case : List[Any] = self.sp_model.serialized_model_proto() fi.write(_lowerCAmelCase ) return (vocab_file,)
352
from __future__ import annotations import math def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : float ): '''simple docstring''' if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) return min( minimax(depth + 1 , node_index * 2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) def __lowerCAmelCase ( ): '''simple docstring''' __snake_case : str = [9_0, 2_3, 6, 3_3, 2_1, 6_5, 1_2_3, 3_4_4_2_3] __snake_case : Optional[Any] = math.log(len(__SCREAMING_SNAKE_CASE ) , 2 ) print("""Optimal value : """ , end="""""" ) print(minimax(0 , 0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
20
0
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class snake_case_ : '''simple docstring''' def __init__( self : List[Any] , _UpperCamelCase : Dict , _UpperCamelCase : List[str]=1_3 , _UpperCamelCase : int=3_2 , _UpperCamelCase : Optional[Any]=2 , _UpperCamelCase : Any=3 , _UpperCamelCase : Optional[int]=1_6 , _UpperCamelCase : Optional[Any]=[1, 2, 1] , _UpperCamelCase : Tuple=[2, 2, 4] , _UpperCamelCase : List[Any]=2 , _UpperCamelCase : Optional[int]=2.0 , _UpperCamelCase : Any=True , _UpperCamelCase : Union[str, Any]=0.0 , _UpperCamelCase : int=0.0 , _UpperCamelCase : Union[str, Any]=0.1 , _UpperCamelCase : List[str]="gelu" , _UpperCamelCase : Union[str, Any]=False , _UpperCamelCase : List[str]=True , _UpperCamelCase : Optional[Any]=0.02 , _UpperCamelCase : List[Any]=1e-5 , _UpperCamelCase : Optional[int]=True , _UpperCamelCase : int=None , _UpperCamelCase : Union[str, Any]=True , _UpperCamelCase : Union[str, Any]=1_0 , _UpperCamelCase : int=8 , _UpperCamelCase : Tuple=["stage1", "stage2", "stage3"] , _UpperCamelCase : Union[str, Any]=[1, 2, 3] , ) ->Any: snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = depths snake_case_ = num_heads snake_case_ = window_size snake_case_ = mlp_ratio snake_case_ = qkv_bias snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = drop_path_rate snake_case_ = hidden_act snake_case_ = use_absolute_embeddings snake_case_ = patch_norm snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = is_training snake_case_ = scope snake_case_ = use_labels snake_case_ = type_sequence_label_size snake_case_ = encoder_stride snake_case_ = out_features snake_case_ = out_indices def snake_case__( self : Tuple ) ->List[Any]: snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = self.get_config() return config, pixel_values, labels def snake_case__( self : List[Any] ) ->Dict: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def snake_case__( self : int , _UpperCamelCase : List[str] , _UpperCamelCase : List[str] , _UpperCamelCase : Any ) ->Any: snake_case_ = MaskFormerSwinModel(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() snake_case_ = model(_UpperCamelCase ) snake_case_ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case_ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def snake_case__( self : Dict , _UpperCamelCase : str , _UpperCamelCase : Tuple , _UpperCamelCase : Tuple ) ->Tuple: snake_case_ = MaskFormerSwinBackbone(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() snake_case_ = model(_UpperCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_UpperCamelCase ): snake_case_ = ['''stem'''] snake_case_ = MaskFormerSwinBackbone(config=_UpperCamelCase ) def snake_case__( self : Tuple ) ->List[Any]: snake_case_ = self.prepare_config_and_inputs() snake_case_, snake_case_, snake_case_ = config_and_inputs snake_case_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case_ ( __A , __A , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE : List[Any] = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : List[Any] = False def snake_case__( self : str ) ->Tuple: snake_case_ = MaskFormerSwinModelTester(self ) snake_case_ = ConfigTester(self , config_class=_UpperCamelCase , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with''' ''' `nn.DataParallel`''' ) ) def snake_case__( self : List[str] ) ->List[str]: pass def snake_case__( self : int ) ->List[str]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case__( self : int ) ->str: return def snake_case__( self : Optional[Any] ) ->Tuple: snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCamelCase ) def snake_case__( self : str ) ->Union[str, Any]: snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_UpperCamelCase ) @unittest.skip('''Swin does not use inputs_embeds''' ) def snake_case__( self : List[str] ) ->Tuple: pass @unittest.skip('''Swin does not support feedforward chunking''' ) def snake_case__( self : List[Any] ) ->str: pass def snake_case__( self : Optional[int] ) ->List[Any]: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(_UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCamelCase , nn.Linear ) ) def snake_case__( self : Optional[int] ) ->Union[str, Any]: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(_UpperCamelCase ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _UpperCamelCase ) @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions''' ) def snake_case__( self : Optional[Any] ) ->List[str]: pass @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone''' ) def snake_case__( self : int ) ->Optional[Any]: pass def snake_case__( self : List[Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : List[str] , _UpperCamelCase : List[Any] , _UpperCamelCase : Optional[Any] ) ->List[Any]: snake_case_ = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) ) snake_case_ = outputs.hidden_states snake_case_ = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_UpperCamelCase ) , _UpperCamelCase ) # Swin has a different seq_length snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def snake_case__( self : List[str] ) ->Optional[int]: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case_ = True self.check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) def snake_case__( self : str ) ->Any: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = 3 snake_case_ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case_ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case_ = True self.check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , (padded_height, padded_width) ) @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints''' ) def snake_case__( self : List[str] ) ->Dict: pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def snake_case__( self : List[Any] ) ->Any: pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def snake_case__( self : List[str] ) ->Optional[Any]: pass def snake_case__( self : Optional[int] ) ->Union[str, Any]: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_UpperCamelCase : Any ): snake_case_ = 0 return t def check_equivalence(_UpperCamelCase : List[Any] , _UpperCamelCase : str , _UpperCamelCase : int , _UpperCamelCase : List[Any]={} ): with torch.no_grad(): snake_case_ = model(**_UpperCamelCase , return_dict=_UpperCamelCase , **_UpperCamelCase ) snake_case_ = model(**_UpperCamelCase , return_dict=_UpperCamelCase , **_UpperCamelCase ).to_tuple() def recursive_check(_UpperCamelCase : Tuple , _UpperCamelCase : List[str] ): if isinstance(_UpperCamelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_UpperCamelCase , _UpperCamelCase ): recursive_check(_UpperCamelCase , _UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_UpperCamelCase , _UpperCamelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_UpperCamelCase ) , set_nan_tensor_to_zero(_UpperCamelCase ) , atol=1e-5 ) , msg=( '''Tuple and dict output are not equal. Difference:''' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_UpperCamelCase ).any()} and `inf`: {torch.isinf(_UpperCamelCase )}. Dict has''' f''' `nan`: {torch.isnan(_UpperCamelCase ).any()} and `inf`: {torch.isinf(_UpperCamelCase )}.''' ) , ) recursive_check(_UpperCamelCase , _UpperCamelCase ) for model_class in self.all_model_classes: snake_case_ = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) check_equivalence(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) check_equivalence(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) check_equivalence(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , {'''output_hidden_states''': True} ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) snake_case_ = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) check_equivalence(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , {'''output_hidden_states''': True} ) @require_torch class snake_case_ ( unittest.TestCase , __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = (MaskFormerSwinBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE : int = MaskFormerSwinConfig def snake_case__( self : Any ) ->Union[str, Any]: snake_case_ = MaskFormerSwinModelTester(self ) def snake_case__( self : Dict ) ->str: snake_case_, snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = inputs_dict['''pixel_values'''].shape[0] for backbone_class in self.all_model_classes: snake_case_ = backbone_class(_UpperCamelCase ) backbone.to(_UpperCamelCase ) backbone.eval() snake_case_ = backbone(**_UpperCamelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _UpperCamelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True snake_case_ = backbone(**_UpperCamelCase , output_hidden_states=_UpperCamelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) snake_case_, snake_case_, snake_case_ = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: snake_case_ = backbone(**_UpperCamelCase , output_attentions=_UpperCamelCase ) self.assertIsNotNone(outputs.attentions )
8
import math def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(SCREAMING_SNAKE_CASE__ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError('''This should never happen''' ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. lowerCAmelCase_ = '''Enter the base and the power separated by a comma: ''' lowerCAmelCase_ , lowerCAmelCase_ = map(int, input(prompt).split(''',''')) lowerCAmelCase_ , lowerCAmelCase_ = map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. lowerCAmelCase_ = res(xa, ya) lowerCAmelCase_ = res(xa, ya) # We check for the largest number if resa > resa: print('''Largest number is''', xa, '''^''', ya) elif resa > resa: print('''Largest number is''', xa, '''^''', ya) else: print('''Both are equal''')
8
1
'''simple docstring''' import os from collections.abc import Iterator def __A ( lowerCAmelCase_ = "." ): for dir_path, dir_names, filenames in os.walk(lowerCAmelCase_ ): _UpperCAmelCase : Tuple = [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(lowerCAmelCase_ )[1] in (".py", ".ipynb"): yield os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ).lstrip("""./""" ) def __A ( lowerCAmelCase_ ): return f"{i * ' '}*" if i else "\n##" def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : Union[str, Any] = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(lowerCAmelCase_ ) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(lowerCAmelCase_ )} {new_part.replace('_' , ' ' ).title()}" ) return new_path def __A ( lowerCAmelCase_ = "." ): _UpperCAmelCase : Dict = """""" for filepath in sorted(good_file_paths(lowerCAmelCase_ ) ): _UpperCAmelCase , _UpperCAmelCase : int = os.path.split(lowerCAmelCase_ ) if filepath != old_path: _UpperCAmelCase : List[str] = print_path(lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Any = (filepath.count(os.sep ) + 1) if filepath else 0 _UpperCAmelCase : Union[str, Any] = f"{filepath}/{filename}".replace(""" """ , """%20""" ) _UpperCAmelCase : Dict = os.path.splitext(filename.replace("""_""" , """ """ ).title() )[0] print(f"{md_prefix(lowerCAmelCase_ )} [{filename}]({url})" ) if __name__ == "__main__": print_directory_md('''.''')
170
'''simple docstring''' from maths.prime_check import is_prime def __A ( lowerCAmelCase_ ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : Optional[Any] = f"Input value of [number={number}] must be an integer" raise TypeError(lowerCAmelCase_ ) if is_prime(lowerCAmelCase_ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
170
1
a__ = '''0.18.2''' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
235
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : str = ["image_processor", "tokenizer"] UpperCAmelCase__ : Optional[int] = "CLIPImageProcessor" UpperCAmelCase__ : Tuple = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self , _a=None , _a=None , **_a ) -> Any: _a : int = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) _a : int = kwargs.pop('''feature_extractor''' ) _a : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a=None , _a=None , _a=None , **_a ) -> List[Any]: 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: _a : str = self.tokenizer(_a , return_tensors=_a , **_a ) if images is not None: _a : Optional[Any] = self.image_processor(_a , return_tensors=_a , **_a ) if text is not None and images is not None: _a : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_a ) , tensor_type=_a ) def __lowercase ( self , *_a , **_a ) -> Optional[Any]: return self.tokenizer.batch_decode(*_a , **_a ) def __lowercase ( self , *_a , **_a ) -> Optional[int]: return self.tokenizer.decode(*_a , **_a ) @property def __lowercase ( self ) -> Optional[int]: _a : Dict = self.tokenizer.model_input_names _a : Dict = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
235
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __UpperCAmelCase :Union[str, Any] = logging.get_logger(__name__) __UpperCAmelCase :Optional[Any] = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class a ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE : str = "trajectory_transformer" SCREAMING_SNAKE_CASE : List[Any] = ["past_key_values"] SCREAMING_SNAKE_CASE : Union[str, Any] = { "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : int , snake_case : Dict=100 , snake_case : Optional[Any]=5 , snake_case : List[str]=1 , snake_case : Tuple=1 , snake_case : str=249 , snake_case : Optional[int]=6 , snake_case : Optional[int]=17 , snake_case : List[str]=25 , snake_case : List[Any]=4 , snake_case : str=4 , snake_case : Any=128 , snake_case : List[Any]=0.1 , snake_case : Dict=0.1 , snake_case : List[Any]=0.1 , snake_case : Optional[int]=0.0_006 , snake_case : List[Any]=512 , snake_case : Optional[int]=0.02 , snake_case : Any=1E-12 , snake_case : Tuple=1 , snake_case : Any=True , snake_case : Optional[Any]=1 , snake_case : Optional[int]=5_0256 , snake_case : Union[str, Any]=5_0256 , **snake_case : Any , ) -> List[str]: __UpperCAmelCase : Union[str, Any] = vocab_size __UpperCAmelCase : int = action_weight __UpperCAmelCase : List[Any] = reward_weight __UpperCAmelCase : Union[str, Any] = value_weight __UpperCAmelCase : Tuple = max_position_embeddings __UpperCAmelCase : List[Any] = block_size __UpperCAmelCase : Tuple = action_dim __UpperCAmelCase : Optional[int] = observation_dim __UpperCAmelCase : Union[str, Any] = transition_dim __UpperCAmelCase : Dict = learning_rate __UpperCAmelCase : int = n_layer __UpperCAmelCase : str = n_head __UpperCAmelCase : Optional[int] = n_embd __UpperCAmelCase : Tuple = embd_pdrop __UpperCAmelCase : Optional[int] = attn_pdrop __UpperCAmelCase : List[str] = resid_pdrop __UpperCAmelCase : Tuple = initializer_range __UpperCAmelCase : Optional[Any] = layer_norm_eps __UpperCAmelCase : Any = kaiming_initializer_range __UpperCAmelCase : List[Any] = use_cache super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case )
240
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class a : """simple docstring""" def __init__( self : Any , snake_case : Any , snake_case : Optional[int]=13 , snake_case : List[str]=7 , snake_case : List[str]=True , snake_case : List[Any]=True , snake_case : int=True , snake_case : Tuple=True , snake_case : int=99 , snake_case : Any=16 , snake_case : Dict=36 , snake_case : Any=6 , snake_case : Dict=6 , snake_case : Dict=6 , snake_case : int=37 , snake_case : int="gelu" , snake_case : str=0.1 , snake_case : Any=0.1 , snake_case : Dict=512 , snake_case : List[Any]=16 , snake_case : Any=2 , snake_case : Any=0.02 , snake_case : Optional[int]=3 , snake_case : List[Any]=4 , snake_case : List[str]=None , ) -> Union[str, Any]: __UpperCAmelCase : str = parent __UpperCAmelCase : List[str] = batch_size __UpperCAmelCase : int = seq_length __UpperCAmelCase : Optional[Any] = is_training __UpperCAmelCase : List[str] = use_input_mask __UpperCAmelCase : List[Any] = use_token_type_ids __UpperCAmelCase : Dict = use_labels __UpperCAmelCase : int = vocab_size __UpperCAmelCase : Optional[int] = embedding_size __UpperCAmelCase : str = hidden_size __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : List[Any] = num_hidden_groups __UpperCAmelCase : Any = num_attention_heads __UpperCAmelCase : int = intermediate_size __UpperCAmelCase : Optional[Any] = hidden_act __UpperCAmelCase : Tuple = hidden_dropout_prob __UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = max_position_embeddings __UpperCAmelCase : List[str] = type_vocab_size __UpperCAmelCase : Any = type_sequence_label_size __UpperCAmelCase : List[Any] = initializer_range __UpperCAmelCase : Dict = num_labels __UpperCAmelCase : str = num_choices __UpperCAmelCase : Union[str, Any] = scope def lowerCamelCase__ ( self : List[Any] ) -> Optional[Any]: __UpperCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : int = None if self.use_input_mask: __UpperCAmelCase : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Dict = None if self.use_token_type_ids: __UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : int = None __UpperCAmelCase : List[str] = None __UpperCAmelCase : Optional[Any] = None if self.use_labels: __UpperCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: return AlbertConfig( 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 , num_hidden_groups=self.num_hidden_groups , ) def lowerCamelCase__ ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : Union[str, Any] , snake_case : int ) -> Optional[int]: __UpperCAmelCase : List[Any] = AlbertModel(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : Tuple = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) __UpperCAmelCase : List[str] = model(snake_case , token_type_ids=snake_case ) __UpperCAmelCase : str = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCamelCase__ ( self : List[str] , snake_case : str , snake_case : Optional[int] , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Dict , snake_case : Optional[int] ) -> Optional[int]: __UpperCAmelCase : str = AlbertForPreTraining(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case , sentence_order_label=snake_case , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def lowerCamelCase__ ( self : Dict , snake_case : Union[str, Any] , snake_case : Dict , snake_case : Any , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Any , snake_case : Tuple ) -> Union[str, Any]: __UpperCAmelCase : Dict = AlbertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : str , snake_case : Tuple , snake_case : List[str] , snake_case : Union[str, Any] , snake_case : List[str] , snake_case : Tuple , snake_case : Optional[Any] , snake_case : Tuple ) -> int: __UpperCAmelCase : Optional[Any] = AlbertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : Optional[Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , start_positions=snake_case , end_positions=snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self : Tuple , snake_case : List[str] , snake_case : Dict , snake_case : Optional[int] , snake_case : Dict , snake_case : int , snake_case : Optional[int] , snake_case : Optional[Any] ) -> Any: __UpperCAmelCase : Optional[int] = self.num_labels __UpperCAmelCase : Any = AlbertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , snake_case : Tuple , snake_case : List[Any] , snake_case : Optional[int] , snake_case : str , snake_case : Dict , snake_case : Union[str, Any] , snake_case : List[str] ) -> int: __UpperCAmelCase : Optional[int] = self.num_labels __UpperCAmelCase : Optional[int] = AlbertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , snake_case : Tuple , snake_case : List[Any] , snake_case : Dict , snake_case : int , snake_case : List[Any] , snake_case : List[Any] , snake_case : Optional[Any] ) -> Tuple: __UpperCAmelCase : Optional[int] = self.num_choices __UpperCAmelCase : List[Any] = AlbertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() __UpperCAmelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[str] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : List[Any] = config_and_inputs __UpperCAmelCase : List[str] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a ( _a , _a , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE : Any = ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE : Any = True def lowerCamelCase__ ( self : Optional[int] , snake_case : Any , snake_case : Dict , snake_case : Tuple=False ) -> Optional[Any]: __UpperCAmelCase : Any = super()._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) if return_labels: if model_class in get_values(snake_case ): __UpperCAmelCase : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=snake_case ) __UpperCAmelCase : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case ) return inputs_dict def lowerCamelCase__ ( self : Dict ) -> int: __UpperCAmelCase : List[Any] = AlbertModelTester(self ) __UpperCAmelCase : Any = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Any ) -> Any: __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def lowerCamelCase__ ( self : Any ) -> Optional[Any]: __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case ) def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Tuple: __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def lowerCamelCase__ ( self : Dict ) -> str: __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def lowerCamelCase__ ( self : List[str] ) -> Tuple: __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def lowerCamelCase__ ( self : str ) -> Any: __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : Tuple = type self.model_tester.create_and_check_model(*snake_case ) @slow def lowerCamelCase__ ( self : Tuple ) -> Optional[int]: for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : List[Any] = AlbertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_torch class a ( unittest.TestCase ): """simple docstring""" @slow def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]: __UpperCAmelCase : Optional[int] = AlbertModel.from_pretrained('''albert-base-v2''' ) __UpperCAmelCase : str = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __UpperCAmelCase : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __UpperCAmelCase : Optional[int] = model(snake_case , attention_mask=snake_case )[0] __UpperCAmelCase : Any = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , snake_case ) __UpperCAmelCase : int = torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case , atol=1E-4 ) )
240
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: lowerCAmelCase: Union[str, Any] = None lowerCAmelCase: Optional[int] = logging.get_logger(__name__) lowerCAmelCase: Tuple = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: Union[str, Any] = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } lowerCAmelCase: List[Any] = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } lowerCAmelCase: int = '▁' class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """token_type_ids"""] lowercase__ = FNetTokenizer def __init__( self : Optional[int] , __snake_case : Optional[Any]=None , __snake_case : Union[str, Any]=None , __snake_case : Dict=False , __snake_case : Optional[Any]=True , __snake_case : Union[str, Any]=True , __snake_case : int="<unk>" , __snake_case : Dict="[SEP]" , __snake_case : List[Any]="<pad>" , __snake_case : List[str]="[CLS]" , __snake_case : Tuple="[MASK]" , **__snake_case : Optional[int] , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. a : Optional[int] = ( AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case , normalized=__snake_case ) if isinstance(__snake_case , __snake_case ) else mask_token ) super().__init__( __snake_case , tokenizer_file=__snake_case , do_lower_case=__snake_case , remove_space=__snake_case , keep_accents=__snake_case , unk_token=__snake_case , sep_token=__snake_case , pad_token=__snake_case , cls_token=__snake_case , mask_token=__snake_case , **__snake_case , ) a : Optional[Any] = do_lower_case a : List[Any] = remove_space a : Dict = keep_accents a : List[Any] = vocab_file a : Optional[int] = False if not self.vocab_file else True def lowercase_ ( self : Any , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : Dict = [self.sep_token_id] a : Any = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowercase_ ( self : Optional[Any] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : List[str] = [self.sep_token_id] a : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): if not os.path.isdir(__snake_case ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a : Optional[Any] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__snake_case ): copyfile(self.vocab_file , __snake_case ) return (out_vocab_file,)
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase : Dict , UpperCAmelCase : Dict ): '''simple docstring''' for e in env_keys: UpperCamelCase__ : List[str] =int(os.environ.get(UpperCAmelCase , -1 ) ) if val >= 0: return val return default def _lowerCAmelCase ( UpperCAmelCase : List[Any] , UpperCAmelCase : Any=False ): '''simple docstring''' UpperCamelCase__ : List[Any] =os.environ.get(UpperCAmelCase , str(UpperCAmelCase ) ) return strtobool(UpperCAmelCase ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowerCAmelCase ( UpperCAmelCase : str , UpperCAmelCase : str="no" ): '''simple docstring''' UpperCamelCase__ : List[str] =os.environ.get(UpperCAmelCase , str(UpperCAmelCase ) ) return value
360
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _SCREAMING_SNAKE_CASE : str = False class __a ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class __a ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase ( self : Optional[int] ): UpperCamelCase__ : Any =VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) UpperCamelCase__ : int =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCamelCase__ : Dict =torch.manual_seed(0 ) UpperCamelCase__ : Optional[int] =pipe.dual_guided( prompt='''first prompt''' , image=lowercase_ , text_to_image_strength=0.7_5 , generator=lowercase_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase_ ) UpperCamelCase__ : str =VersatileDiffusionPipeline.from_pretrained(lowercase_ , torch_dtype=torch.floataa ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) UpperCamelCase__ : int =generator.manual_seed(0 ) UpperCamelCase__ : str =pipe.dual_guided( prompt='''first prompt''' , image=lowercase_ , text_to_image_strength=0.7_5 , generator=lowercase_ , 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 : Optional[Any] ): UpperCamelCase__ : Dict =VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) UpperCamelCase__ : str ='''cyberpunk 2077''' UpperCamelCase__ : str =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCamelCase__ : int =torch.manual_seed(0 ) UpperCamelCase__ : int =pipe.dual_guided( prompt=lowercase_ , image=lowercase_ , text_to_image_strength=0.7_5 , generator=lowercase_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCamelCase__ : List[str] =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) UpperCamelCase__ : Dict =np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 UpperCamelCase__ : Dict ='''A painting of a squirrel eating a burger ''' UpperCamelCase__ : Optional[int] =torch.manual_seed(0 ) UpperCamelCase__ : str =pipe.text_to_image( prompt=lowercase_ , generator=lowercase_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCamelCase__ : str =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) UpperCamelCase__ : List[Any] =np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 UpperCamelCase__ : Optional[Any] =pipe.image_variation(lowercase_ , generator=lowercase_ , output_type='''numpy''' ).images UpperCamelCase__ : str =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) UpperCamelCase__ : Tuple =np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
157
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCAmelCase ( self ) -> Union[str, Any]: lowerCAmelCase_ :Union[str, Any] = 1 lowerCAmelCase_ :Any = 3 lowerCAmelCase_ :Tuple = (32, 32) lowerCAmelCase_ :Dict = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__A ) return image @property def __lowerCAmelCase ( self ) -> Any: torch.manual_seed(0 ) lowerCAmelCase_ :Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) return model @property def __lowerCAmelCase ( self ) -> List[Any]: torch.manual_seed(0 ) lowerCAmelCase_ :Optional[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCAmelCase ( self ) -> Tuple: torch.manual_seed(0 ) lowerCAmelCase_ :Optional[Any] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(__A ) @property def __lowerCAmelCase ( self ) -> int: def extract(*__A , **__A ): class _SCREAMING_SNAKE_CASE : def __init__( self ) -> str: lowerCAmelCase_ :List[str] = torch.ones([0] ) def __lowerCAmelCase ( self , __A ) -> int: self.pixel_values.to(__A ) return self return Out() return extract def __lowerCAmelCase ( self ) -> str: lowerCAmelCase_ :List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase_ :Dict = self.dummy_cond_unet lowerCAmelCase_ :List[Any] = PNDMScheduler(skip_prk_steps=__A ) lowerCAmelCase_ :int = self.dummy_vae lowerCAmelCase_ :Union[str, Any] = self.dummy_text_encoder lowerCAmelCase_ :Optional[int] = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) lowerCAmelCase_ :Dict = 77 lowerCAmelCase_ :Tuple = self.dummy_image.to(__A ) lowerCAmelCase_ :Any = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk lowerCAmelCase_ :Dict = AltDiffusionImgaImgPipeline( unet=__A , scheduler=__A , vae=__A , text_encoder=__A , tokenizer=__A , safety_checker=__A , feature_extractor=self.dummy_extractor , ) lowerCAmelCase_ :Dict = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__A ) lowerCAmelCase_ :Any = alt_pipe.to(__A ) alt_pipe.set_progress_bar_config(disable=__A ) lowerCAmelCase_ :Optional[Any] = """A painting of a squirrel eating a burger""" lowerCAmelCase_ :Optional[Any] = torch.Generator(device=__A ).manual_seed(0 ) lowerCAmelCase_ :List[Any] = alt_pipe( [prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , image=__A , ) lowerCAmelCase_ :Tuple = output.images lowerCAmelCase_ :str = torch.Generator(device=__A ).manual_seed(0 ) lowerCAmelCase_ :str = alt_pipe( [prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , image=__A , return_dict=__A , )[0] lowerCAmelCase_ :Tuple = image[0, -3:, -3:, -1] lowerCAmelCase_ :List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase_ :str = np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCAmelCase ( self ) -> Optional[int]: lowerCAmelCase_ :Tuple = self.dummy_cond_unet lowerCAmelCase_ :int = PNDMScheduler(skip_prk_steps=__A ) lowerCAmelCase_ :int = self.dummy_vae lowerCAmelCase_ :Dict = self.dummy_text_encoder lowerCAmelCase_ :List[Any] = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) lowerCAmelCase_ :Optional[Any] = 77 lowerCAmelCase_ :Optional[int] = self.dummy_image.to(__A ) # put models in fp16 lowerCAmelCase_ :Any = unet.half() lowerCAmelCase_ :Union[str, Any] = vae.half() lowerCAmelCase_ :Optional[Any] = bert.half() # make sure here that pndm scheduler skips prk lowerCAmelCase_ :Tuple = AltDiffusionImgaImgPipeline( unet=__A , scheduler=__A , vae=__A , text_encoder=__A , tokenizer=__A , safety_checker=__A , feature_extractor=self.dummy_extractor , ) lowerCAmelCase_ :List[str] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__A ) lowerCAmelCase_ :Union[str, Any] = alt_pipe.to(__A ) alt_pipe.set_progress_bar_config(disable=__A ) lowerCAmelCase_ :int = """A painting of a squirrel eating a burger""" lowerCAmelCase_ :Dict = torch.manual_seed(0 ) lowerCAmelCase_ :Union[str, Any] = alt_pipe( [prompt] , generator=__A , num_inference_steps=2 , output_type="""np""" , image=__A , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCAmelCase ( self ) -> Optional[int]: lowerCAmelCase_ :List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) # resize to resolution that is divisible by 8 but not 16 or 32 lowerCAmelCase_ :Tuple = init_image.resize((760, 504) ) lowerCAmelCase_ :str = """BAAI/AltDiffusion""" lowerCAmelCase_ :str = AltDiffusionImgaImgPipeline.from_pretrained( __A , safety_checker=__A , ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() lowerCAmelCase_ :Any = """A fantasy landscape, trending on artstation""" lowerCAmelCase_ :Dict = torch.manual_seed(0 ) lowerCAmelCase_ :str = pipe( prompt=__A , image=__A , strength=0.7_5 , guidance_scale=7.5 , generator=__A , output_type="""np""" , ) lowerCAmelCase_ :Dict = output.images[0] lowerCAmelCase_ :List[str] = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) lowerCAmelCase_ :int = np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) -> Any: lowerCAmelCase_ :Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) lowerCAmelCase_ :Union[str, Any] = init_image.resize((768, 512) ) lowerCAmelCase_ :str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy""" ) lowerCAmelCase_ :Union[str, Any] = """BAAI/AltDiffusion""" lowerCAmelCase_ :Any = AltDiffusionImgaImgPipeline.from_pretrained( __A , safety_checker=__A , ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() lowerCAmelCase_ :Tuple = """A fantasy landscape, trending on artstation""" lowerCAmelCase_ :int = torch.manual_seed(0 ) lowerCAmelCase_ :Tuple = pipe( prompt=__A , image=__A , strength=0.7_5 , guidance_scale=7.5 , generator=__A , output_type="""np""" , ) lowerCAmelCase_ :Optional[int] = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
84
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' UpperCAmelCase_ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' UpperCAmelCase_ : int = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any="binary" ) -> Dict: """simple docstring""" UpperCamelCase :List[str] = simple_accuracy(__magic_name__ , __magic_name__ ) UpperCamelCase :Dict = float(fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average=__magic_name__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase :Optional[Any] = {} for id_pred, label in zip(__magic_name__ , __magic_name__ ): UpperCamelCase :str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCamelCase :Union[str, Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase :Dict = [(pred, label)] UpperCamelCase , UpperCamelCase :Optional[int] = [], [] for question, preds_labels in question_map.items(): UpperCamelCase , UpperCamelCase :Optional[Any] = zip(*__magic_name__ ) UpperCamelCase :Optional[int] = fa_score(y_true=__magic_name__ , y_pred=__magic_name__ , average="""macro""" ) fas.append(__magic_name__ ) UpperCamelCase :int = int(sum(pred == label for pred, label in preds_labels ) == len(__magic_name__ ) ) ems.append(__magic_name__ ) UpperCamelCase :Optional[int] = float(sum(__magic_name__ ) / len(__magic_name__ ) ) UpperCamelCase :str = sum(__magic_name__ ) / len(__magic_name__ ) UpperCamelCase :Tuple = float(fa_score(y_true=__magic_name__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : str ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _A ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _A ( self : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : str ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCamelCase :Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCamelCase :Tuple = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
38
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case : Tuple = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : str = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
207
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : Optional[int], lowerCAmelCase_ : Any, lowerCAmelCase_ : List[Any], lowerCAmelCase_ : Tuple ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file __lowerCAmelCase = TapasConfig.from_json_file(lowerCAmelCase_ ) # set absolute/relative position embeddings parameter __lowerCAmelCase = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __lowerCAmelCase = TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "WTQ": # run_task_main.py hparams __lowerCAmelCase = 4 __lowerCAmelCase = True # hparam_utils.py hparams __lowerCAmelCase = 0.66_4694 __lowerCAmelCase = 0.20_7951 __lowerCAmelCase = 0.12_1194 __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = False __lowerCAmelCase = 0.035_2513 __lowerCAmelCase = TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __lowerCAmelCase = 4 __lowerCAmelCase = False # hparam_utils.py hparams __lowerCAmelCase = 36.4519 __lowerCAmelCase = 0.90_3421 __lowerCAmelCase = 222.088 __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = 0.76_3141 __lowerCAmelCase = TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "TABFACT": __lowerCAmelCase = TapasForSequenceClassification(config=lowerCAmelCase_ ) elif task == "MLM": __lowerCAmelCase = TapasForMaskedLM(config=lowerCAmelCase_ ) elif task == "INTERMEDIATE_PRETRAINING": __lowerCAmelCase = TapasModel(config=lowerCAmelCase_ ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(lowerCAmelCase_ ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) __lowerCAmelCase = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt', model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase_ ) print('Used relative position embeddings:', model.config.reset_position_index_per_cell ) if __name__ == "__main__": _snake_case : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _snake_case : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
207
1
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def UpperCAmelCase ( lowercase = 3 ): """simple docstring""" if isinstance(lowercase , lowercase ): raise TypeError('''number of qubits must be a integer.''' ) if number_of_qubits <= 0: raise ValueError('''number of qubits must be > 0.''' ) if math.floor(lowercase ) != number_of_qubits: raise ValueError('''number of qubits must be exact integer.''' ) if number_of_qubits > 10: raise ValueError('''number of qubits too large to simulate(>10).''' ) __lowercase = QuantumRegister(lowercase , '''qr''' ) __lowercase = ClassicalRegister(lowercase , '''cr''' ) __lowercase = QuantumCircuit(lowercase , lowercase ) __lowercase = number_of_qubits for i in range(lowercase ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase , lowercase ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase , lowercase ) # simulate with 10000 shots __lowercase = Aer.get_backend('''qasm_simulator''' ) __lowercase = execute(lowercase , lowercase , shots=10000 ) return job.result().get_counts(lowercase ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
210
import qiskit def UpperCAmelCase ( lowercase , lowercase ): """simple docstring""" __lowercase = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register __lowercase = qiskit.QuantumCircuit(lowercase , lowercase ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowercase = qiskit.execute(lowercase , lowercase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowercase ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
210
1
"""simple docstring""" def lowercase ( a__ : Any ) -> list[list]: _UpperCamelCase = current_set.copy() for row_index, row in enumerate(__UpperCAmelCase ): _UpperCamelCase = row[0] for column_index, column in enumerate(__UpperCAmelCase ): if magnitude == 0: _UpperCamelCase = column continue _UpperCamelCase = column / magnitude # Subtract to cancel term _UpperCamelCase = current_set[0] _UpperCamelCase = [first_row] _UpperCamelCase = current_set[1::] for row in current_set: _UpperCamelCase = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCAmelCase ) continue for column_index in range(len(__UpperCAmelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCAmelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: _UpperCamelCase = final_set[0] _UpperCamelCase = [] _UpperCamelCase = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _UpperCamelCase = simplify(__UpperCAmelCase ) for i in range(len(__UpperCAmelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCAmelCase ) _UpperCamelCase = resultant return final_set def lowercase ( a__ : List[Any] ) -> list: if len(__UpperCAmelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) _UpperCamelCase = len(__UpperCAmelCase ) + 1 if any(len(__UpperCAmelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCAmelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCAmelCase ) == 1: return [equations[0][-1] / equations[0][0]] _UpperCamelCase = equations.copy() if any(0 in row for row in data_set ): _UpperCamelCase = data_set.copy() _UpperCamelCase = [] for row_index, row in enumerate(__UpperCAmelCase ): if 0 not in row: _UpperCamelCase = data_set.pop(__UpperCAmelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCAmelCase ) _UpperCamelCase = data_set.copy() _UpperCamelCase = simplify(__UpperCAmelCase ) _UpperCamelCase = simplified[::-1] _UpperCamelCase = [] for row in simplified: _UpperCamelCase = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _UpperCamelCase = row.copy()[: len(__UpperCAmelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCAmelCase ) == 0: solutions.append(0 ) continue _UpperCamelCase = temp_row[1::] _UpperCamelCase = temp_row[::-1] for column_index, column in enumerate(__UpperCAmelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCAmelCase ) _UpperCamelCase = [] for item in solutions: final.append(float(round(__UpperCAmelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
355
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore UpperCAmelCase = """ Human: <<task>> Assistant: """ UpperCAmelCase = """huggingface-tools/default-prompts""" UpperCAmelCase = {"""chat""": """chat_prompt_template.txt""", """run""": """run_prompt_template.txt"""} def lowercase ( a__ : int , a__ : int , a__ : Any="run" ) -> Any: if prompt_or_repo_id is None: _UpperCamelCase = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('''\\s''' , a__ ) is not None: return prompt_or_repo_id _UpperCamelCase = cached_file( a__ , PROMPT_FILES[mode] , repo_type='''dataset''' , user_agent={'''agent''': agent_name} ) with open(a__ , '''r''' , encoding='''utf-8''' ) as f: return f.read()
54
0
from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 lowerCAmelCase_ = { # 1536-bit 5: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, # 2048-bit 1_4: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AACAA68FFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, # 3072-bit 1_5: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, # 4096-bit 1_6: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7''' + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA''' + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6''' + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED''' + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9''' + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199''' + '''FFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, # 6144-bit 1_7: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08''' + '''8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B''' + '''302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9''' + '''A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6''' + '''49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8''' + '''FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C''' + '''180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718''' + '''3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D''' + '''04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D''' + '''B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226''' + '''1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC''' + '''E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26''' + '''99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB''' + '''04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2''' + '''233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127''' + '''D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492''' + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406''' + '''AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918''' + '''DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151''' + '''2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03''' + '''F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F''' + '''BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA''' + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B''' + '''B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632''' + '''387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E''' + '''6DCC4024FFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, # 8192-bit 1_8: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7''' + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA''' + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6''' + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED''' + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9''' + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492''' + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD''' + '''F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831''' + '''179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B''' + '''DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF''' + '''5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6''' + '''D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3''' + '''23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA''' + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328''' + '''06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C''' + '''DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE''' + '''12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4''' + '''38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300''' + '''741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568''' + '''3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9''' + '''22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B''' + '''4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A''' + '''062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36''' + '''4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1''' + '''B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92''' + '''4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47''' + '''9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71''' + '''60C980DD98EDD3DFFFFFFFFFFFFFFFFF''', base=1_6, ), '''generator''': 2, }, } class __lowerCAmelCase : def __init__(self , __magic_name__ = 14 ) -> None: '''simple docstring''' if group not in primes: raise ValueError('''Unsupported Group''' ) snake_case_ : Union[str, Any] = primes[group]["prime"] snake_case_ : Optional[int] = primes[group]["generator"] snake_case_ : Dict = int(hexlify(urandom(32 ) ) , base=16 ) def lowerCamelCase (self ) -> str: '''simple docstring''' return hex(self.__private_key )[2:] def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = pow(self.generator , self.__private_key , self.prime ) return hex(UpperCAmelCase_ )[2:] def lowerCamelCase (self , __magic_name__ ) -> bool: '''simple docstring''' return ( 2 <= key <= self.prime - 2 and pow(UpperCAmelCase_ , (self.prime - 1) // 2 , self.prime ) == 1 ) def lowerCamelCase (self , __magic_name__ ) -> str: '''simple docstring''' snake_case_ : int = int(UpperCAmelCase_ , base=16 ) if not self.is_valid_public_key(UpperCAmelCase_ ): raise ValueError('''Invalid public key''' ) snake_case_ : Dict = pow(UpperCAmelCase_ , self.__private_key , self.prime ) return shaaaa(str(UpperCAmelCase_ ).encode() ).hexdigest() @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> bool: '''simple docstring''' return ( 2 <= remote_public_key_str <= prime - 2 and pow(UpperCAmelCase_ , (prime - 1) // 2 , UpperCAmelCase_ ) == 1 ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ = 14 ) -> str: '''simple docstring''' snake_case_ : Dict = int(UpperCAmelCase_ , base=16 ) snake_case_ : str = int(UpperCAmelCase_ , base=16 ) snake_case_ : Union[str, Any] = primes[group]["prime"] if not DiffieHellman.is_valid_public_key_static(UpperCAmelCase_ , UpperCAmelCase_ ): raise ValueError('''Invalid public key''' ) snake_case_ : List[Any] = pow(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return shaaaa(str(UpperCAmelCase_ ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
279
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __A = "." if __name__ == "__main__": __A = os.path.join(REPO_PATH, "utils/documentation_tests.txt") __A = [] __A = [] with open(doctest_file_path) as fp: for line in fp: __A = line.strip() __A = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __A = "\n".join(non_existent_paths) raise ValueError(f'`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}') if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
10
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : Union[str, Any] = '''realm''' def __init__( self : List[Any] , lowerCAmelCase__ : Optional[int]=3_0_5_2_2 , lowerCAmelCase__ : Tuple=7_6_8 , lowerCAmelCase__ : Optional[int]=1_2_8 , lowerCAmelCase__ : List[str]=1_2 , lowerCAmelCase__ : int=1_2 , lowerCAmelCase__ : List[str]=8 , lowerCAmelCase__ : str=3_0_7_2 , lowerCAmelCase__ : str="gelu_new" , lowerCAmelCase__ : Dict=0.1 , lowerCAmelCase__ : Union[str, Any]=0.1 , lowerCAmelCase__ : int=5_1_2 , lowerCAmelCase__ : str=2 , lowerCAmelCase__ : List[Any]=0.02 , lowerCAmelCase__ : str=1e-12 , lowerCAmelCase__ : Union[str, Any]=2_5_6 , lowerCAmelCase__ : str=1_0 , lowerCAmelCase__ : Dict=1e-3 , lowerCAmelCase__ : Any=5 , lowerCAmelCase__ : int=3_2_0 , lowerCAmelCase__ : List[str]=1_3_3_5_3_7_1_8 , lowerCAmelCase__ : List[str]=5_0_0_0 , lowerCAmelCase__ : str=1 , lowerCAmelCase__ : Dict=0 , lowerCAmelCase__ : Dict=2 , **lowerCAmelCase__ : Union[str, Any] , ) -> str: """simple docstring""" super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) # Common config _UpperCAmelCase : Optional[Any] = vocab_size _UpperCAmelCase : Dict = max_position_embeddings _UpperCAmelCase : Tuple = hidden_size _UpperCAmelCase : Union[str, Any] = retriever_proj_size _UpperCAmelCase : Tuple = num_hidden_layers _UpperCAmelCase : Optional[Any] = num_attention_heads _UpperCAmelCase : Any = num_candidates _UpperCAmelCase : str = intermediate_size _UpperCAmelCase : List[str] = hidden_act _UpperCAmelCase : Tuple = hidden_dropout_prob _UpperCAmelCase : int = attention_probs_dropout_prob _UpperCAmelCase : Any = initializer_range _UpperCAmelCase : List[Any] = type_vocab_size _UpperCAmelCase : List[str] = layer_norm_eps # Reader config _UpperCAmelCase : List[str] = span_hidden_size _UpperCAmelCase : Optional[Any] = max_span_width _UpperCAmelCase : Optional[Any] = reader_layer_norm_eps _UpperCAmelCase : int = reader_beam_size _UpperCAmelCase : Optional[int] = reader_seq_len # Retrieval config _UpperCAmelCase : Dict = num_block_records _UpperCAmelCase : Any = searcher_beam_size
17
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') __a = logging.getLogger(__name__) @dataclass class A__ : """simple docstring""" UpperCamelCase_ : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCamelCase_ : Optional[str] = field( default=UpperCamelCase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase_ : Optional[str] = field( default=UpperCamelCase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase_ : Optional[str] = field( default=UpperCamelCase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCamelCase_ : bool = field( default=UpperCamelCase , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) UpperCamelCase_ : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCamelCase_ : bool = field( default=UpperCamelCase , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) @dataclass class A__ : """simple docstring""" UpperCamelCase_ : Optional[str] = field(default=UpperCamelCase , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase_ : Optional[str] = field( default=UpperCamelCase , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase_ : bool = field( default=UpperCamelCase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) UpperCamelCase_ : Optional[int] = field( default=UpperCamelCase , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) UpperCamelCase_ : Optional[int] = field( default=UpperCamelCase , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. If passed, sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCamelCase_ : bool = field( default=UpperCamelCase , metadata={ '''help''': ( '''Whether to pad all samples to the maximum sentence length. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch. More ''' '''efficient on GPU but very bad for TPU.''' ) } , ) UpperCamelCase_ : Optional[int] = field( default=UpperCamelCase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCamelCase_ : Optional[int] = field( default=UpperCamelCase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def _lowerCAmelCase ( self : Any ) -> Any: """simple docstring""" if self.train_file is not None: _UpperCAmelCase : List[Any] = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: _UpperCAmelCase : List[str] = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class A__ : """simple docstring""" UpperCamelCase_ : PreTrainedTokenizerBase UpperCamelCase_ : Union[bool, str, PaddingStrategy] = True UpperCamelCase_ : Optional[int] = None UpperCamelCase_ : Optional[int] = None def __call__( self : List[Any] , lowerCAmelCase__ : List[str] ) -> List[str]: """simple docstring""" _UpperCAmelCase : int = "label" if "label" in features[0].keys() else "labels" _UpperCAmelCase : Dict = [feature.pop(lowerCAmelCase__ ) for feature in features] _UpperCAmelCase : str = len(lowerCAmelCase__ ) _UpperCAmelCase : int = len(features[0]["input_ids"] ) _UpperCAmelCase : str = [ [{k: v[i] for k, v in feature.items()} for i in range(lowerCAmelCase__ )] for feature in features ] _UpperCAmelCase : List[str] = list(chain(*lowerCAmelCase__ ) ) _UpperCAmelCase : Any = self.tokenizer.pad( lowerCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten _UpperCAmelCase : Any = {k: v.view(lowerCAmelCase__ , lowerCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels _UpperCAmelCase : List[str] = torch.tensor(lowerCAmelCase__ , dtype=torch.intaa ) return batch def __UpperCAmelCase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _UpperCAmelCase : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag", a_, a_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _UpperCAmelCase : Optional[int] = training_args.get_process_log_level() logger.setLevel(a_ ) datasets.utils.logging.set_verbosity(a_ ) transformers.utils.logging.set_verbosity(a_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. _UpperCAmelCase : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCAmelCase : Any = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: _UpperCAmelCase : Union[str, Any] = {} if data_args.train_file is not None: _UpperCAmelCase : str = data_args.train_file if data_args.validation_file is not None: _UpperCAmelCase : Optional[Any] = data_args.validation_file _UpperCAmelCase : Dict = data_args.train_file.split("." )[-1] _UpperCAmelCase : Optional[int] = load_dataset( a_, data_files=a_, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) else: # Downloading and loading the swag dataset from the hub. _UpperCAmelCase : Dict = load_dataset( "swag", "regular", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCAmelCase : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) _UpperCAmelCase : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) _UpperCAmelCase : str = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path ), config=a_, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # When using your own dataset or a different dataset from swag, you will probably need to change this. _UpperCAmelCase : Optional[Any] = [f"""ending{i}""" for i in range(4 )] _UpperCAmelCase : List[Any] = "sent1" _UpperCAmelCase : Optional[int] = "sent2" if data_args.max_seq_length is None: _UpperCAmelCase : List[str] = tokenizer.model_max_length if max_seq_length > 1_024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) _UpperCAmelCase : Dict = 1_024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) _UpperCAmelCase : Dict = min(data_args.max_seq_length, tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(a_: Union[str, Any] ): _UpperCAmelCase : Optional[int] = [[context] * 4 for context in examples[context_name]] _UpperCAmelCase : Tuple = examples[question_header_name] _UpperCAmelCase : Optional[Any] = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(a_ ) ] # Flatten out _UpperCAmelCase : List[str] = list(chain(*a_ ) ) _UpperCAmelCase : Dict = list(chain(*a_ ) ) # Tokenize _UpperCAmelCase : List[Any] = tokenizer( a_, a_, truncation=a_, max_length=a_, padding="max_length" if data_args.pad_to_max_length else False, ) # Un-flatten return {k: [v[i : i + 4] for i in range(0, len(a_ ), 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) _UpperCAmelCase : int = raw_datasets["train"] if data_args.max_train_samples is not None: _UpperCAmelCase : Optional[Any] = min(len(a_ ), data_args.max_train_samples ) _UpperCAmelCase : List[Any] = train_dataset.select(range(a_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): _UpperCAmelCase : Union[str, Any] = train_dataset.map( a_, batched=a_, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) _UpperCAmelCase : Dict = raw_datasets["validation"] if data_args.max_eval_samples is not None: _UpperCAmelCase : int = min(len(a_ ), data_args.max_eval_samples ) _UpperCAmelCase : List[str] = eval_dataset.select(range(a_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): _UpperCAmelCase : Optional[int] = eval_dataset.map( a_, batched=a_, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) # Data collator _UpperCAmelCase : Tuple = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=a_, pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(a_: Tuple ): _UpperCAmelCase , _UpperCAmelCase : Tuple = eval_predictions _UpperCAmelCase : Union[str, Any] = np.argmax(a_, axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer _UpperCAmelCase : Any = Trainer( model=a_, args=a_, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=a_, data_collator=a_, compute_metrics=a_, ) # Training if training_args.do_train: _UpperCAmelCase : Optional[Any] = None if training_args.resume_from_checkpoint is not None: _UpperCAmelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCAmelCase : List[str] = last_checkpoint _UpperCAmelCase : Any = trainer.train(resume_from_checkpoint=a_ ) trainer.save_model() # Saves the tokenizer too for easy upload _UpperCAmelCase : str = train_result.metrics _UpperCAmelCase : List[str] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(a_ ) ) _UpperCAmelCase : Union[str, Any] = min(a_, len(a_ ) ) trainer.log_metrics("train", a_ ) trainer.save_metrics("train", a_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) _UpperCAmelCase : List[Any] = trainer.evaluate() _UpperCAmelCase : int = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(a_ ) _UpperCAmelCase : Tuple = min(a_, len(a_ ) ) trainer.log_metrics("eval", a_ ) trainer.save_metrics("eval", a_ ) _UpperCAmelCase : int = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**a_ ) else: trainer.create_model_card(**a_ ) def __UpperCAmelCase ( a_: int ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
17
1
from __future__ import annotations def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): return [ord(SCREAMING_SNAKE_CASE__ ) - 96 for elem in plain] def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): return "".join(chr(elem + 96 ) for elem in encoded ) def __SCREAMING_SNAKE_CASE (): snake_case_ = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''' , SCREAMING_SNAKE_CASE__ ) print('''Decoded:''' , decode(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": main()
8
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __SCREAMING_SNAKE_CASE (*SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = list(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): snake_case_ = 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 __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = [ '''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 __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 128 ): if function is None: return functools.partial(SCREAMING_SNAKE_CASE__ , starting_batch_size=SCREAMING_SNAKE_CASE__ ) snake_case_ = starting_batch_size def decorator(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): 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() snake_case_ = list(inspect.signature(SCREAMING_SNAKE_CASE__ ).parameters.keys() ) # Guard against user error if len(SCREAMING_SNAKE_CASE__ ) < (len(SCREAMING_SNAKE_CASE__ ) + 1): snake_case_ = ''', '''.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
8
1
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration SCREAMING_SNAKE_CASE :Optional[int] = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = ["layers", "blocks"] for k in ignore_keys: state_dict.pop(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE :Union[str, Any] = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" __A = list(s_dict.keys() ) for key in keys: __A = key for k, v in WHISPER_MAPPING.items(): if k in key: __A = new_key.replace(_lowercase , _lowercase ) print(F'''{key} -> {new_key}''' ) __A = s_dict.pop(_lowercase ) return s_dict def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = emb.weight.shape __A = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) __A = emb.weight.data return lin_layer def UpperCAmelCase ( a_ , a_ ) -> bytes: """simple docstring""" os.makedirs(_lowercase , exist_ok=_lowercase ) __A = os.path.basename(_lowercase ) __A = url.split("/" )[-2] __A = os.path.join(_lowercase , _lowercase ) if os.path.exists(_lowercase ) and not os.path.isfile(_lowercase ): raise RuntimeError(F'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_lowercase ): __A = open(_lowercase , "rb" ).read() if hashlib.shaaaa(_lowercase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(F'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_lowercase ) as source, open(_lowercase , "wb" ) as output: with tqdm( total=int(source.info().get("Content-Length" ) ) , ncols=8_0 , unit="iB" , unit_scale=_lowercase , unit_divisor=1_0_2_4 ) as loop: while True: __A = source.read(8_1_9_2 ) if not buffer: break output.write(_lowercase ) loop.update(len(_lowercase ) ) __A = open(_lowercase , "rb" ).read() if hashlib.shaaaa(_lowercase ).hexdigest() != expected_shaaaa: raise RuntimeError( "Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model." ) return model_bytes def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" if ".pt" not in checkpoint_path: __A = _download(_MODELS[checkpoint_path] ) else: __A = torch.load(_lowercase , map_location="cpu" ) __A = original_checkpoint["dims"] __A = original_checkpoint["model_state_dict"] __A = state_dict["decoder.token_embedding.weight"] remove_ignore_keys_(_lowercase ) rename_keys(_lowercase ) __A = True __A = state_dict["decoder.layers.0.fc1.weight"].shape[0] __A = WhisperConfig( vocab_size=dimensions["n_vocab"] , encoder_ffn_dim=_lowercase , decoder_ffn_dim=_lowercase , num_mel_bins=dimensions["n_mels"] , d_model=dimensions["n_audio_state"] , max_target_positions=dimensions["n_text_ctx"] , encoder_layers=dimensions["n_audio_layer"] , encoder_attention_heads=dimensions["n_audio_head"] , decoder_layers=dimensions["n_text_layer"] , decoder_attention_heads=dimensions["n_text_state"] , max_source_positions=dimensions["n_audio_ctx"] , ) __A = WhisperForConditionalGeneration(_lowercase ) __A = model.model.load_state_dict(_lowercase , strict=_lowercase ) if len(_lowercase ) > 0 and not set(_lowercase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( "Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing," F''' but all the following weights are missing {missing}''' ) if tie_embeds: __A = make_linear_from_emb(model.model.decoder.embed_tokens ) else: __A = proj_out_weights model.save_pretrained(_lowercase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Union[str, Any] = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
363
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging SCREAMING_SNAKE_CASE :Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Union[str, Any] = { 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "bloom" snake_case_ = ["past_key_values"] snake_case_ = { "num_hidden_layers": "n_layer", "num_attention_heads": "n_head", } def __init__( self : Optional[Any] ,A : List[Any]=25_08_80 ,A : Optional[int]=64 ,A : List[Any]=2 ,A : Optional[int]=8 ,A : str=1E-5 ,A : str=0.02 ,A : int=True ,A : Optional[Any]=1 ,A : int=2 ,A : str=False ,A : Dict=0.0 ,A : List[Any]=0.0 ,A : str=1 ,A : List[Any]=False ,**A : List[Any] ,): __A = vocab_size # Backward compatibility with n_embed kwarg __A = kwargs.pop("n_embed" ,A ) __A = hidden_size if n_embed is None else n_embed __A = n_layer __A = n_head __A = layer_norm_epsilon __A = initializer_range __A = use_cache __A = pretraining_tp __A = apply_residual_connection_post_layernorm __A = hidden_dropout __A = attention_dropout __A = bos_token_id __A = eos_token_id __A = slow_but_exact super().__init__(bos_token_id=A ,eos_token_id=A ,**A ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.12" ) def __init__( self : str ,A : PretrainedConfig ,A : str = "default" ,A : List[PatchingSpec] = None ,A : bool = False ,): super().__init__(A ,task=A ,patching_specs=A ,use_past=A ) if not getattr(self._config ,"pad_token_id" ,A ): # TODO: how to do that better? __A = 0 @property def UpperCamelCase_ ( self : Union[str, Any] ): __A = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(A ,direction="inputs" ,inverted_values_shape=A ) __A = {0: "batch", 1: "past_sequence + sequence"} else: __A = {0: "batch", 1: "sequence"} return common_inputs @property def UpperCamelCase_ ( self : Optional[Any] ): return self._config.n_layer @property def UpperCamelCase_ ( self : List[Any] ): return self._config.n_head @property def UpperCamelCase_ ( self : Optional[int] ): return 1E-3 def UpperCamelCase_ ( self : Any ,A : "PreTrainedTokenizer" ,A : int = -1 ,A : int = -1 ,A : bool = False ,A : Optional["TensorType"] = None ,): __A = super(A ,self ).generate_dummy_inputs( A ,batch_size=A ,seq_length=A ,is_pair=A ,framework=A ) # We need to order the input in the way they appears in the forward() __A = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __A , __A = common_inputs["input_ids"].shape # Not using the same length for past_key_values __A = seqlen + 2 __A = self._config.hidden_size // self.num_attention_heads __A = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) __A = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) __A = [ (torch.zeros(A ), torch.zeros(A )) for _ in range(self.num_layers ) ] __A = common_inputs["attention_mask"] if self.use_past: __A = ordered_inputs["attention_mask"].dtype __A = torch.cat( [ordered_inputs["attention_mask"], torch.ones(A ,A ,dtype=A )] ,dim=1 ) return ordered_inputs @property def UpperCamelCase_ ( self : int ): return 13
124
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def a ( __a ) -> bool: '''simple docstring''' UpperCamelCase__ :int = int(number**0.5 ) return number == sq * sq def a ( __a , __a , __a , __a , __a , __a ) -> tuple[int, int]: '''simple docstring''' UpperCamelCase__ :int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase__ :int = x_den * y_den * z_den UpperCamelCase__ :int = gcd(__a , __a ) top //= hcf bottom //= hcf return top, bottom def a ( __a = 35 ) -> int: '''simple docstring''' UpperCamelCase__ :set = set() UpperCamelCase__ :int UpperCamelCase__ :Fraction = Fraction(0 ) UpperCamelCase__ :tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCamelCase__ :int = x_num * y_den + x_den * y_num UpperCamelCase__ :Any = x_den * y_den UpperCamelCase__ :Tuple = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :List[str] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase__ :Dict = x_den * x_den * y_den * y_den if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Optional[int] = int(sqrt(__a ) ) UpperCamelCase__ :int = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=-1 UpperCamelCase__ :Tuple = x_num * y_num UpperCamelCase__ :Union[str, Any] = x_den * y_num + x_num * y_den UpperCamelCase__ :List[str] = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Union[str, Any] = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :Optional[Any] = x_num * x_num * y_num * y_num UpperCamelCase__ :Tuple = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :str = int(sqrt(__a ) ) UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Dict = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :int = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) for num, den in unique_s: total += Fraction(__a , __a ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
97
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
def _lowerCAmelCase ( __snake_case : int ) -> Dict: __A : str = '' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def _lowerCAmelCase ( __snake_case : Tuple ) -> Tuple: __A : List[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key __A : Optional[int] = remove_duplicates(key.upper() ) __A : Union[str, Any] = len(lowercase__ ) # First fill cipher with key characters __A : str = {alphabet[i]: char for i, char in enumerate(lowercase__ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(lowercase__ ) , 26 ): __A : Union[str, Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 __A : List[Any] = alphabet[i - offset] __A : Optional[Any] = char return cipher_alphabet def _lowerCAmelCase ( __snake_case : Dict , __snake_case : Optional[int] ) -> Tuple: return "".join(cipher_map.get(lowercase__ , lowercase__ ) for ch in message.upper() ) def _lowerCAmelCase ( __snake_case : Any , __snake_case : Optional[Any] ) -> Dict: __A : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(lowercase__ , lowercase__ ) for ch in message.upper() ) def _lowerCAmelCase ( ) -> int: __A : Dict = input('Enter message to encode or decode: ' ).strip() __A : Union[str, Any] = input('Enter keyword: ' ).strip() __A : Union[str, Any] = input('Encipher or decipher? E/D:' ).strip()[0].lower() try: __A : int = {'e': encipher, 'd': decipher}[option] except KeyError: raise KeyError('invalid input option' ) __A : Union[str, Any] = create_cipher_map(lowercase__ ) print(func(lowercase__ , lowercase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
363
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel lowercase__ : Optional[int] = HfApi() lowercase__ : Dict = {} # fmt: off lowercase__ : List[str] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) lowercase__ : Tuple = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) lowercase__ : Optional[Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) lowercase__ : List[Any] = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) lowercase__ : Dict = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) lowercase__ : Optional[int] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) lowercase__ : List[Any] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) lowercase__ : List[str] = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) lowercase__ : Dict = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) lowercase__ : Optional[int] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) lowercase__ : List[str] = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) lowercase__ : Optional[int] = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) lowercase__ : int = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) lowercase__ : int = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) lowercase__ : List[Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on lowercase__ : str = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": lowercase__ : int = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(f"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): lowercase__ : Optional[Any] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: lowercase__ : Tuple = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) lowercase__ : List[str] = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) lowercase__ : int = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): lowercase__ : Tuple = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1e-3 ) print(f"""{mod.modelId} has passed successfully!!!""")
190
0
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version a__ : str = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if got_ver is None or want_ver is None: raise ValueError( f"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" f""" reinstalling {pkg}.""" ) if not ops[op](version.parse(lowerCAmelCase_ ) , version.parse(lowerCAmelCase_ ) ): raise ImportError( f"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""\n{hint}""" if hint is not None else "" # non-versioned check if re.match(R"^[\w_\-\d]+$" , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = requirement, None, None else: __SCREAMING_SNAKE_CASE = re.findall(R"^([^!=<>\s]+)([\s!=<>]{1,2}.+)" , lowerCAmelCase_ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" f""" got {requirement}""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_full.split("," ) # there could be multiple requirements __SCREAMING_SNAKE_CASE = {} for w in want_range: __SCREAMING_SNAKE_CASE = re.findall(R"^([\s!=<>]{1,2})(.+)" , lowerCAmelCase_ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," f""" but got {requirement}""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = match[0] __SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(f"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": __SCREAMING_SNAKE_CASE = ".".join([str(lowerCAmelCase_ ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return # check if any version is installed try: __SCREAMING_SNAKE_CASE = importlib.metadata.version(lowerCAmelCase_ ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(lowerCAmelCase_ , lowerCAmelCase_ )
54
"""simple docstring""" class _UpperCAmelCase: def __init__( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = {} def UpperCAmelCase ( self) -> None: '''simple docstring''' print(self.vertex) for i in self.vertex: print(__a , ''' -> ''' , ''' -> '''.join([str(__a) for j in self.vertex[i]])) def UpperCAmelCase ( self , __a , __a) -> None: '''simple docstring''' # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(__a) else: # else make a new vertex _UpperCamelCase = [to_vertex] def UpperCAmelCase ( self) -> None: '''simple docstring''' # visited array for storing already visited nodes _UpperCamelCase = [False] * len(self.vertex) # call the recursive helper function for i in range(len(self.vertex)): if not visited[i]: self.dfs_recursive(__a , __a) def UpperCAmelCase ( self , __a , __a) -> None: '''simple docstring''' # mark start vertex as visited _UpperCamelCase = True print(__a , end=''' ''') # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__a , __a) if __name__ == "__main__": _a = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
194
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 ViTImageProcessor class a__ ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=3 , lowerCamelCase_=2_24 , lowerCamelCase_=30 , lowerCamelCase_=4_00 , lowerCamelCase_=True , lowerCamelCase_=None , lowerCamelCase_=True , lowerCamelCase_=[0.5, 0.5, 0.5] , lowerCamelCase_=[0.5, 0.5, 0.5] , ) -> Optional[int]: lowerCAmelCase__ = size if size is not None else {'''height''': 18, '''width''': 18} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean lowerCAmelCase__ = image_std def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class a__ ( a__ , unittest.TestCase ): '''simple docstring''' lowercase__ : List[Any] = ViTImageProcessor if is_vision_available() else None def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: lowerCAmelCase__ = EfficientFormerImageProcessorTester(self ) @property def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: return self.image_proc_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE ( self ) -> int: lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase_ , '''image_mean''' ) ) self.assertTrue(hasattr(lowerCamelCase_ , '''image_std''' ) ) self.assertTrue(hasattr(lowerCamelCase_ , '''do_normalize''' ) ) self.assertTrue(hasattr(lowerCamelCase_ , '''do_resize''' ) ) self.assertTrue(hasattr(lowerCamelCase_ , '''size''' ) ) def __SCREAMING_SNAKE_CASE ( self ) -> Any: pass def __SCREAMING_SNAKE_CASE ( self ) -> int: # Initialize image_processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase__ = image_processor(lowerCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: # Initialize image_processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=lowerCamelCase_ , numpify=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , np.ndarray ) # Test not batched input lowerCAmelCase__ = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase__ = image_processor(lowerCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # Initialize image_processor lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=lowerCamelCase_ , torchify=lowerCamelCase_ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase_ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase__ = image_processor(lowerCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
371
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging __UpperCAmelCase = logging.get_logger(__name__) class a__ ( a__ ): '''simple docstring''' lowercase__ : int = "linear" lowercase__ : Any = "cosine" lowercase__ : Optional[int] = "cosine_with_restarts" lowercase__ : Optional[Any] = "polynomial" lowercase__ : Tuple = "constant" lowercase__ : Optional[int] = "constant_with_warmup" lowercase__ : Optional[int] = "piecewise_constant" def _snake_case ( A , A = -1 ) -> Any: return LambdaLR(A , lambda A : 1 , last_epoch=A ) def _snake_case ( A , A , A = -1 ) -> Optional[Any]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1.0 , A ) ) return 1.0 return LambdaLR(A , A , last_epoch=A ) def _snake_case ( A , A , A = -1 ) -> Union[str, Any]: lowerCAmelCase__ = {} lowerCAmelCase__ = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: lowerCAmelCase__ , lowerCAmelCase__ = rule_str.split(''':''' ) lowerCAmelCase__ = int(A ) lowerCAmelCase__ = float(A ) lowerCAmelCase__ = value lowerCAmelCase__ = float(rule_list[-1] ) def create_rules_function(A , A ): def rule_func(A ) -> float: lowerCAmelCase__ = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(A ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func lowerCAmelCase__ = create_rules_function(A , A ) return LambdaLR(A , A , last_epoch=A ) def _snake_case ( A , A , A , A=-1 ) -> Optional[int]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A = 0.5 , A = -1 ) -> List[str]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) lowerCAmelCase__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(A ) * 2.0 * progress )) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A = 1 , A = -1 ) -> Union[str, Any]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) lowerCAmelCase__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(A ) * progress) % 1.0) )) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A=1E-7 , A=1.0 , A=-1 ) -> Union[str, Any]: lowerCAmelCase__ = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(F"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: lowerCAmelCase__ = lr_init - lr_end lowerCAmelCase__ = num_training_steps - num_warmup_steps lowerCAmelCase__ = 1 - (current_step - num_warmup_steps) / decay_steps lowerCAmelCase__ = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(A , A , A ) __UpperCAmelCase = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def _snake_case ( A , A , A = None , A = None , A = None , A = 1 , A = 1.0 , A = -1 , ) -> int: lowerCAmelCase__ = SchedulerType(A ) lowerCAmelCase__ = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(A , last_epoch=A ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(A , step_rules=A , last_epoch=A ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(A , num_warmup_steps=A , last_epoch=A ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( A , num_warmup_steps=A , num_training_steps=A , num_cycles=A , last_epoch=A , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( A , num_warmup_steps=A , num_training_steps=A , power=A , last_epoch=A , ) return schedule_func( A , num_warmup_steps=A , num_training_steps=A , last_epoch=A )
228
0
import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor __UpperCamelCase : str = logging.get_logger(__name__) class lowercase__ ( __A): def __init__( self : Tuple , *UpperCamelCase__ : Any , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' warnings.warn( '''The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use OwlViTImageProcessor instead.''' , _UpperCamelCase , ) super().__init__(*_UpperCamelCase , **_UpperCamelCase )
182
import math def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(SCREAMING_SNAKE_CASE__ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError('''This should never happen''' ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. lowerCAmelCase_ = '''Enter the base and the power separated by a comma: ''' lowerCAmelCase_ , lowerCAmelCase_ = map(int, input(prompt).split(''',''')) lowerCAmelCase_ , lowerCAmelCase_ = map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. lowerCAmelCase_ = res(xa, ya) lowerCAmelCase_ = res(xa, ya) # We check for the largest number if resa > resa: print('''Largest number is''', xa, '''^''', ya) elif resa > resa: print('''Largest number is''', xa, '''^''', ya) else: print('''Both are equal''')
8
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCAmelCase = {"configuration_speech_encoder_decoder": ["SpeechEncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["SpeechEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["FlaxSpeechEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
370
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] ): __magic_name__ = [] __magic_name__ = 0 __magic_name__ = 0 def snake_case__ ( self : int ): return self.head == self.tail def snake_case__ ( self : int , a__ : Any ): self.data.append(a__ ) __magic_name__ = self.tail + 1 def snake_case__ ( self : Tuple ): __magic_name__ = self.data[self.head] __magic_name__ = self.head + 1 return ret def snake_case__ ( self : Optional[Any] ): return self.tail - self.head def snake_case__ ( self : List[Any] ): print(self.data ) print('''**************''' ) print(self.data[self.head : self.tail] ) class _SCREAMING_SNAKE_CASE : def __init__( self : List[str] , a__ : Any ): __magic_name__ = data __magic_name__ = None __magic_name__ = None __magic_name__ = 1 def snake_case__ ( self : Optional[int] ): return self.data def snake_case__ ( self : List[Any] ): return self.left def snake_case__ ( self : Tuple ): return self.right def snake_case__ ( self : Any ): return self.height def snake_case__ ( self : Optional[Any] , a__ : Any ): __magic_name__ = data def snake_case__ ( self : int , a__ : MyNode | None ): __magic_name__ = node def snake_case__ ( self : Tuple , a__ : MyNode | None ): __magic_name__ = node def snake_case__ ( self : List[str] , a__ : int ): __magic_name__ = height def UpperCamelCase ( a ) -> int: '''simple docstring''' if node is None: return 0 return node.get_height() def UpperCamelCase ( a , a ) -> int: '''simple docstring''' if a > b: return a return b def UpperCamelCase ( a ) -> MyNode: '''simple docstring''' print('''left rotation node:''' , node.get_data() ) __magic_name__ = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(a ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) __magic_name__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def UpperCamelCase ( a ) -> MyNode: '''simple docstring''' print('''right rotation node:''' , node.get_data() ) __magic_name__ = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(a ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) __magic_name__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def UpperCamelCase ( a ) -> MyNode: '''simple docstring''' __magic_name__ = node.get_left() assert left_child is not None node.set_left(left_rotation(a ) ) return right_rotation(a ) def UpperCamelCase ( a ) -> MyNode: '''simple docstring''' __magic_name__ = node.get_right() assert right_child is not None node.set_right(right_rotation(a ) ) return left_rotation(a ) def UpperCamelCase ( a , a ) -> MyNode | None: '''simple docstring''' if node is None: return MyNode(a ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , a ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected __magic_name__ = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child __magic_name__ = right_rotation(a ) else: __magic_name__ = lr_rotation(a ) else: node.set_right(insert_node(node.get_right() , a ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: __magic_name__ = node.get_right() assert right_child is not None if data < right_child.get_data(): __magic_name__ = rl_rotation(a ) else: __magic_name__ = left_rotation(a ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) return node def UpperCamelCase ( a ) -> Any: '''simple docstring''' while True: __magic_name__ = root.get_right() if right_child is None: break __magic_name__ = right_child return root.get_data() def UpperCamelCase ( a ) -> Any: '''simple docstring''' while True: __magic_name__ = root.get_left() if left_child is None: break __magic_name__ = left_child return root.get_data() def UpperCamelCase ( a , a ) -> MyNode | None: '''simple docstring''' __magic_name__ = root.get_left() __magic_name__ = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: __magic_name__ = get_left_most(a ) root.set_data(a ) root.set_right(del_node(a , a ) ) elif left_child is not None: __magic_name__ = left_child elif right_child is not None: __magic_name__ = right_child else: return None elif root.get_data() > data: if left_child is None: print('''No such data''' ) return root else: root.set_left(del_node(a , a ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(a , a ) ) if get_height(a ) - get_height(a ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): __magic_name__ = left_rotation(a ) else: __magic_name__ = rl_rotation(a ) elif get_height(a ) - get_height(a ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): __magic_name__ = right_rotation(a ) else: __magic_name__ = lr_rotation(a ) __magic_name__ = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(a ) return root class _SCREAMING_SNAKE_CASE : def __init__( self : List[Any] ): __magic_name__ = None def snake_case__ ( self : List[Any] ): return get_height(self.root ) def snake_case__ ( self : Optional[int] , a__ : Any ): print('''insert:''' + str(a__ ) ) __magic_name__ = insert_node(self.root , a__ ) def snake_case__ ( self : Dict , a__ : Any ): print('''delete:''' + str(a__ ) ) if self.root is None: print('''Tree is empty!''' ) return __magic_name__ = del_node(self.root , a__ ) def __str__( self : Optional[Any] , ): # a level traversale, gives a more intuitive look on the tree __magic_name__ = '''''' __magic_name__ = MyQueue() q.push(self.root ) __magic_name__ = self.get_height() if layer == 0: return output __magic_name__ = 0 while not q.is_empty(): __magic_name__ = q.pop() __magic_name__ = ''' ''' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(a__ ) q.push(a__ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space __magic_name__ = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , a__ ) - 1: __magic_name__ = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def UpperCamelCase ( ) -> None: '''simple docstring''' import doctest doctest.testmod() if __name__ == "__main__": _test() _lowerCAmelCase = AVLtree() _lowerCAmelCase = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
98
0
"""simple docstring""" from collections import deque class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a ): __a = process_name # process name __a = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __a = arrival_time __a = burst_time # remaining burst time __a = 0 # total time of the process wait in ready queue __a = 0 # time from arrival time to completion time class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a , _a , ): # total number of mlfq's queues __a = number_of_queues # time slice of queues that round robin algorithm applied __a = time_slices # unfinished process is in this ready_queue __a = queue # current time __a = current_time # finished process is in this sequence queue __a = deque() def __UpperCAmelCase ( self ): __a = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): completion_times.append(queue[i].stop_time ) return completion_times def __UpperCAmelCase ( self , _a ): return [q.burst_time for q in queue] def __UpperCAmelCase ( self , _a ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __UpperCAmelCase ( self , _a ): __a = deque() # sequence deque of finished process while len(_a ) != 0: __a = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(_a ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __a = 0 # set the process's turnaround time because it is finished __a = self.current_time - cp.arrival_time # set the completion time __a = self.current_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __UpperCAmelCase ( self , _a , _a ): __a = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(_a ) ): __a = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(_a ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __a = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(_a ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __a = 0 # set the finish time __a = self.current_time # update the process' turnaround time because it is finished __a = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __UpperCAmelCase ( self ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): __a , __a = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest lowercase_ = Process("P1", 0, 5_3) lowercase_ = Process("P2", 0, 1_7) lowercase_ = Process("P3", 0, 6_8) lowercase_ = Process("P4", 0, 2_4) lowercase_ = 3 lowercase_ = [1_7, 2_5] lowercase_ = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([Pa, Pa, Pa, Pa])}) lowercase_ = Process("P1", 0, 5_3) lowercase_ = Process("P2", 0, 1_7) lowercase_ = Process("P3", 0, 6_8) lowercase_ = Process("P4", 0, 2_4) lowercase_ = 3 lowercase_ = [1_7, 2_5] lowercase_ = deque([Pa, Pa, Pa, Pa]) lowercase_ = MLFQ(number_of_queues, time_slices, queue, 0) lowercase_ = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( F'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( F'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( F'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
45
'''simple docstring''' from math import factorial, pi def A_ ( snake_case , snake_case = 30 ): if not isinstance(snake_case , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(snake_case , snake_case ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) SCREAMING_SNAKE_CASE:Optional[int] = float(snake_case ) SCREAMING_SNAKE_CASE:Optional[Any] = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(snake_case ) ) def A_ ( snake_case , snake_case = 30 ): if not isinstance(snake_case , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(snake_case , snake_case ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) SCREAMING_SNAKE_CASE:Optional[Any] = float(snake_case ) SCREAMING_SNAKE_CASE:List[str] = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(snake_case ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
139
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer lowerCAmelCase : List[str] = logging.get_logger(__name__) lowerCAmelCase : List[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase : Optional[Any] = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : Optional[int] = { """yjernite/retribert-base-uncased""": 512, } lowerCAmelCase : List[Any] = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = RetriBertTokenizer __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ): """simple docstring""" super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , tokenize_chinese_chars=_a , strip_accents=_a , **_a , ) lowerCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _a ) != do_lower_case or normalizer_state.get("""strip_accents""" , _a ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _a ) != tokenize_chinese_chars ): lowerCamelCase = getattr(_a , normalizer_state.pop("""type""" ) ) lowerCamelCase = do_lower_case lowerCamelCase = strip_accents lowerCamelCase = tokenize_chinese_chars lowerCamelCase = normalizer_class(**_a ) lowerCamelCase = do_lower_case def _lowerCAmelCase ( self , _a , _a=None ): """simple docstring""" lowerCamelCase = [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 , _a , _a = None ): """simple docstring""" lowerCamelCase = [self.sep_token_id] lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
352
"""simple docstring""" def a__ ( snake_case__ , snake_case__ ) -> int: return number | (1 << position) def a__ ( snake_case__ , snake_case__ ) -> int: return number & ~(1 << position) def a__ ( snake_case__ , snake_case__ ) -> int: return number ^ (1 << position) def a__ ( snake_case__ , snake_case__ ) -> bool: return ((number >> position) & 1) == 1 def a__ ( snake_case__ , snake_case__ ) -> int: return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
168
0
from cva import destroyAllWindows, imread, imshow, waitKey def lowerCamelCase_ ( lowerCamelCase__ ): # getting number of pixels in the image lowerCamelCase_ , lowerCamelCase_ = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(lowerCamelCase__ ): for j in range(lowerCamelCase__ ): lowerCamelCase_ = [2_5_5, 2_5_5, 2_5_5] - img[i][j] return img if __name__ == "__main__": # read original image __A =imread('''image_data/lena.jpg''', 1) # convert to its negative __A =convert_to_negative(img) # show result image imshow('''negative of original image''', img) waitKey(0) destroyAllWindows()
19
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase__ ( A , unittest.TestCase ): """simple docstring""" __a = None __a = BloomTokenizerFast __a = BloomTokenizerFast __a = True __a = False __a = """tokenizer_file""" __a = {"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""} def lowerCamelCase__ ( self : int ): '''simple docstring''' super().setUp() __UpperCAmelCase : Any = BloomTokenizerFast.from_pretrained("""bigscience/tokenizer""" ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self : Any , **UpperCamelCase : Optional[int] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase ) def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' __UpperCAmelCase : Any = self.get_rust_tokenizer() __UpperCAmelCase : Optional[Any] = ["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""] __UpperCAmelCase : int = [[2_175, 23_714, 73_173, 144_252, 2], [77, 132_619, 3_478, 368, 109_586, 35_433, 2]] __UpperCAmelCase : Dict = tokenizer.batch_encode_plus(UpperCamelCase )["""input_ids"""] self.assertListEqual(UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : int = tokenizer.batch_decode(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : int , UpperCamelCase : Any=6 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __UpperCAmelCase : Optional[int] = self.rust_tokenizer_class.from_pretrained(UpperCamelCase , **UpperCamelCase ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input __UpperCAmelCase : Dict = """This is a simple input""" __UpperCAmelCase : str = ["""This is a simple input 1""", """This is a simple input 2"""] __UpperCAmelCase : List[str] = ("""This is a simple input""", """This is a pair""") __UpperCAmelCase : Dict = [ ("""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 try: tokenizer_r.encode(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.encode_plus(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.batch_encode_plus(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.encode(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.batch_encode_plus(UpperCamelCase , max_length=UpperCamelCase ) except ValueError: self.fail("""Bloom Tokenizer should be able to deal with padding""" ) __UpperCAmelCase : Union[str, Any] = None # Hotfixing padding = None self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Simple input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Simple input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" , ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Pair input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" , ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self.get_rust_tokenizer() __UpperCAmelCase : Optional[Any] = load_dataset("""xnli""" , """all_languages""" , split="""test""" , streaming=UpperCamelCase ) __UpperCAmelCase : Optional[Any] = next(iter(UpperCamelCase ) )["""premise"""] # pick up one data __UpperCAmelCase : Any = list(sample_data.values() ) __UpperCAmelCase : Optional[Any] = list(map(tokenizer.encode , UpperCamelCase ) ) __UpperCAmelCase : List[Any] = [tokenizer.decode(UpperCamelCase , clean_up_tokenization_spaces=UpperCamelCase ) for x in output_tokens] self.assertListEqual(UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
115
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a__ : @staticmethod def __SCREAMING_SNAKE_CASE ( *UpperCAmelCase , **UpperCAmelCase ) -> List[Any]: pass @is_pipeline_test @require_torch @require_vision class a__ ( unittest.TestCase ): A__ : Tuple = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: __a = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) __a = [ { 'image': Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'question': 'How many cats are there?', }, { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'question': 'How many cats are there?', }, ] return vqa_pipeline, examples def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: __a = vqa_pipeline(UpperCAmelCase , top_k=1 ) self.assertEqual( UpperCAmelCase , [ [{'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}], [{'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}], ] , ) @require_torch def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: __a = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) __a = './tests/fixtures/tests_samples/COCO/000000039769.png' __a = 'How many cats are there?' __a = vqa_pipeline(image=UpperCAmelCase , question='How many cats are there?' , top_k=2 ) self.assertEqual( UpperCAmelCase , [{'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}, {'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}] ) __a = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( UpperCAmelCase , [{'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}, {'score': ANY(UpperCAmelCase ), 'answer': ANY(UpperCAmelCase )}] ) @slow @require_torch def __SCREAMING_SNAKE_CASE ( self ) -> int: __a = pipeline('visual-question-answering' , model='dandelin/vilt-b32-finetuned-vqa' ) __a = './tests/fixtures/tests_samples/COCO/000000039769.png' __a = 'How many cats are there?' __a = vqa_pipeline(image=UpperCAmelCase , question=UpperCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase , decimals=4 ) , [{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) __a = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase , decimals=4 ) , [{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) __a = vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase , decimals=4 ) , [[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2 , ) @require_tf @unittest.skip('Visual question answering not implemented in TF' ) def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: pass
364
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCamelCase_ : Dict = {"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""SpeechEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""FlaxSpeechEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys lowerCamelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
197
0
import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class _SCREAMING_SNAKE_CASE : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , )-> List[Any]: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_token_type_ids lowerCamelCase_ =use_input_mask lowerCamelCase_ =use_labels lowerCamelCase_ =use_mc_token_ids lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =num_labels lowerCamelCase_ =num_choices lowerCamelCase_ =scope lowerCamelCase_ =self.vocab_size - 1 def _snake_case ( self )-> Dict: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ =None if self.use_input_mask: lowerCamelCase_ =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ =None if self.use_token_type_ids: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase_ =None if self.use_mc_token_ids: lowerCamelCase_ =ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ =ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ =self.get_config() lowerCamelCase_ =ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def _snake_case ( self )-> Optional[int]: return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =CTRLModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =CTRLLMHeadModel(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) =config_and_inputs lowerCamelCase_ ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =self.num_labels lowerCamelCase_ =CTRLForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() lowerCamelCase_ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ =model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:Optional[Any] = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () _UpperCamelCase:List[Any] = (CTRLLMHeadModel,) if is_torch_available() else () _UpperCamelCase:str = ( { "feature-extraction": CTRLModel, "text-classification": CTRLForSequenceClassification, "text-generation": CTRLLMHeadModel, "zero-shot": CTRLForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase:Union[str, Any] = True _UpperCamelCase:Any = False _UpperCamelCase:int = False def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Tuple: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def _snake_case ( self )-> List[Any]: lowerCamelCase_ =CTRLModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , n_embd=37 ) def _snake_case ( self )-> str: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def _snake_case ( self )-> str: self.config_tester.run_common_tests() def _snake_case ( self )-> int: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self )-> Tuple: pass @slow def _snake_case ( self )-> Any: for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =CTRLModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def _snake_case ( self )-> Any: pass @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> Tuple: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def _snake_case ( self )-> Any: lowerCamelCase_ =CTRLLMHeadModel.from_pretrained("""ctrl""" ) model.to(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) # Legal the president is lowerCamelCase_ =[ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a lowerCamelCase_ =model.generate(_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE ) self.assertListEqual(output_ids[0].tolist() , _SCREAMING_SNAKE_CASE )
154
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __A : Dict = logging.get_logger(__name__) def __UpperCamelCase ( _A : Union[str, Any] ) ->List[str]: """simple docstring""" lowerCamelCase_ =MobileNetVaConfig(layer_norm_eps=0.0_0_1 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) lowerCamelCase_ =re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""" , _A ) if matches: lowerCamelCase_ =float(matches[1] ) lowerCamelCase_ =int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". lowerCamelCase_ =1001 lowerCamelCase_ ="""imagenet-1k-id2label.json""" lowerCamelCase_ ="""huggingface/label-files""" lowerCamelCase_ =json.load(open(hf_hub_download(_A , _A , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase_ ={int(_A ) + 1: v for k, v in idalabel.items()} lowerCamelCase_ ="""background""" lowerCamelCase_ =idalabel lowerCamelCase_ ={v: k for k, v in idalabel.items()} return config def __UpperCamelCase ( ) ->int: """simple docstring""" lowerCamelCase_ ="""http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase_ =Image.open(requests.get(_A , stream=_A ).raw ) return im @torch.no_grad() def __UpperCamelCase ( _A : List[Any] , _A : Any , _A : str , _A : int=False ) ->List[str]: """simple docstring""" lowerCamelCase_ =get_mobilenet_va_config(_A ) # Load 🤗 model lowerCamelCase_ =MobileNetVaForImageClassification(_A ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(_A , _A , _A ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor lowerCamelCase_ =MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size} , size={"""shortest_edge""": config.image_size + 32} , ) lowerCamelCase_ =image_processor(images=prepare_img() , return_tensors="""pt""" ) lowerCamelCase_ =model(**_A ) lowerCamelCase_ =outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": lowerCamelCase_ =torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ) elif model_name == "mobilenet_v1_0.75_192": lowerCamelCase_ =torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3] ) else: lowerCamelCase_ =None if expected_logits is not None: assert torch.allclose(logits[0, :3] , _A , atol=1E-4 ) Path(_A ).mkdir(exist_ok=_A ) print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(_A ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(_A ) if push_to_hub: print("""Pushing to the hub...""" ) lowerCamelCase_ ="""google/""" + model_name image_processor.push_to_hub(_A ) model.push_to_hub(_A ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __A : List[str] = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
154
1
'''simple docstring''' def _A ( snake_case = 4_00_00_00 ) -> int: _lowercase : Any = [] _lowercase : Union[str, Any] = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(snake_case ) _lowercase : Union[str, Any] = b, a + b return sum(snake_case ) if __name__ == "__main__": print(F'''{solution() = }''')
370
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
199
0
def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->Union[str, Any]: """simple docstring""" lowercase : Union[str, Any] = [False] * len(_UpperCamelCase ) lowercase : Optional[int] = [] queue.append(_UpperCamelCase ) lowercase : Union[str, Any] = True while queue: lowercase : List[str] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(_UpperCamelCase ) lowercase : Tuple = True lowercase : Optional[Any] = u return visited[t] def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->List[str]: """simple docstring""" lowercase : List[str] = [-1] * (len(_UpperCamelCase )) lowercase : int = 0 while bfs(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ): lowercase : List[str] = float('''Inf''' ) lowercase : int = sink while s != source: # Find the minimum value in select path lowercase : List[Any] = min(_UpperCamelCase, graph[parent[s]][s] ) lowercase : Union[str, Any] = parent[s] max_flow += path_flow lowercase : Optional[int] = sink while v != source: lowercase : Any = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow lowercase : Union[str, Any] = parent[v] return max_flow __a = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] __a , __a = 0, 5 print(ford_fulkerson(graph, source, sink))
337
import os import re import shutil import sys import tempfile import unittest import black __a = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. __a = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCamelCase ( self ): lowercase : str = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) lowercase : Any = self.diffusers_dir shutil.copy( os.path.join(SCREAMING_SNAKE_CASE__ , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def __lowerCamelCase ( self ): lowercase : List[Any] = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): lowercase : Tuple = comment + f"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: lowercase : str = comment + f"""\nclass {class_name}(nn.Module):\n""" + overwrite_result lowercase : Any = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) lowercase : List[Any] = black.format_str(SCREAMING_SNAKE_CASE__ , mode=SCREAMING_SNAKE_CASE__ ) lowercase : Dict = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , newline='''\n''' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE__ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: self.assertTrue(f.read() , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): lowercase : Tuple = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , SCREAMING_SNAKE_CASE__ , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , SCREAMING_SNAKE_CASE__ ) , ) # Copy consistency with a really long name lowercase : List[Any] = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( f"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , f"""{long_class_name}SchedulerOutput""" , re.sub('''Bert''' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , SCREAMING_SNAKE_CASE__ , overwrite_result=re.sub('''DDPM''' , '''Test''' , SCREAMING_SNAKE_CASE__ ) , )
337
1
"""simple docstring""" # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : List[Any] ={ "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] a__ : List[Any] ={ "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } a__ : Optional[int] =f'''{src_lang}-{tgt_lang}''' a__ : Any =f''' --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = "facebook/wmt19-{src_lang}-{tgt_lang}" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = "{texts[src_lang]}" input_ids = tokenizer.encode(input, return_tensors="pt") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR\'s WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) ''' os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) a__ : Tuple =os.path.join(SCREAMING_SNAKE_CASE , "README.md" ) print(f'''Generating {path}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE ) # make sure we are under the root of the project UpperCAmelCase : str = Path(__file__).resolve().parent.parent.parent UpperCAmelCase : Dict = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: UpperCAmelCase : List[str] = model_name.split("""-""") UpperCAmelCase : Tuple = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
357
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" a__ : Tuple =set() a__ : Optional[Any] =[] def parse_line(SCREAMING_SNAKE_CASE : Optional[int] ): for line in fp: if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : str =line.decode("UTF-8" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(" " ): # process a single warning and move it to `selected_warnings`. if len(SCREAMING_SNAKE_CASE ) > 0: a__ : Union[str, Any] ="\n".join(SCREAMING_SNAKE_CASE ) # Only keep the warnings specified in `targets` if any(f''': {x}: ''' in warning for x in targets ): selected_warnings.add(SCREAMING_SNAKE_CASE ) buffer.clear() continue else: a__ : Optional[Any] =line.strip() buffer.append(SCREAMING_SNAKE_CASE ) if from_gh: for filename in os.listdir(SCREAMING_SNAKE_CASE ): a__ : str =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): # read the file if filename != "warnings.txt": continue with open(SCREAMING_SNAKE_CASE ) as fp: parse_line(SCREAMING_SNAKE_CASE ) else: try: with zipfile.ZipFile(SCREAMING_SNAKE_CASE ) as z: for filename in z.namelist(): if not os.path.isdir(SCREAMING_SNAKE_CASE ): # read the file if filename != "warnings.txt": continue with z.open(SCREAMING_SNAKE_CASE ) as fp: parse_line(SCREAMING_SNAKE_CASE ) except Exception: logger.warning( f'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[int] =set() a__ : Any =[os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for p in os.listdir(SCREAMING_SNAKE_CASE ) if (p.endswith(".zip" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) return selected_warnings if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" return values.split("," ) UpperCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) UpperCAmelCase : List[Any] = parser.parse_args() UpperCAmelCase : str = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links UpperCAmelCase : Dict = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts UpperCAmelCase : Tuple = extract_warnings(args.output_dir, args.targets) UpperCAmelCase : Optional[Any] = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
148
0
"""simple docstring""" import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _UpperCamelCase : List[Any] = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def a_ ( ): '''simple docstring''' lowercase__ : Dict = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowercase__ : int = get_sagemaker_input() else: lowercase__ : List[str] = get_cluster_input() return config def a_ ( _lowerCAmelCase : List[Any]=None ): '''simple docstring''' if subparsers is not None: lowercase__ : Union[str, Any] = subparsers.add_parser('config' , description=snake_case_ ) else: lowercase__ : Tuple = argparse.ArgumentParser('Accelerate config command' , description=snake_case_ ) parser.add_argument( '--config_file' , default=snake_case_ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case_ ) return parser def a_ ( _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : Optional[int] = get_user_input() if args.config_file is not None: lowercase__ : Dict = args.config_file else: if not os.path.isdir(snake_case_ ): os.makedirs(snake_case_ ) lowercase__ : Optional[Any] = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case_ ) else: config.to_yaml_file(snake_case_ ) print(f"""accelerate configuration saved at {config_file}""" ) def a_ ( ): '''simple docstring''' lowercase__ : Tuple = config_command_parser() lowercase__ : Tuple = parser.parse_args() config_command(snake_case_ ) if __name__ == "__main__": main()
77
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = {"""tokenizer_file""": """tokenizer.json"""} lowerCAmelCase = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class A_ ( A__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = ["""input_ids""", """attention_mask"""] SCREAMING_SNAKE_CASE_ = None def __init__( self :Dict , lowerCamelCase_ :Union[str, Any]=None , lowerCamelCase_ :Any=None , lowerCamelCase_ :int=None , lowerCamelCase_ :List[str]="<unk>" , lowerCamelCase_ :List[Any]="<s>" , lowerCamelCase_ :str="</s>" , lowerCamelCase_ :Union[str, Any]="<pad>" , lowerCamelCase_ :Union[str, Any]=False , lowerCamelCase_ :Dict=False , **lowerCamelCase_ :List[Any] , ): """simple docstring""" super().__init__( lowerCamelCase_ , lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , unk_token=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , add_prefix_space=lowerCamelCase_ , clean_up_tokenization_spaces=lowerCamelCase_ , **lowerCamelCase_ , ) lowerCamelCase__ : List[str] =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , lowerCamelCase_ ) != add_prefix_space: lowerCamelCase__ : str =getattr(lowerCamelCase_ , pre_tok_state.pop('type' ) ) lowerCamelCase__ : List[Any] =add_prefix_space lowerCamelCase__ : Optional[Any] =pre_tok_class(**lowerCamelCase_ ) lowerCamelCase__ : Any =add_prefix_space def UpperCAmelCase__ ( self :Optional[int] , *lowerCamelCase_ :List[str] , **lowerCamelCase_ :Optional[Any] ): """simple docstring""" lowerCamelCase__ : List[Any] =kwargs.get('is_split_into_words' , lowerCamelCase_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" ' pretokenized inputs.' ) return super()._batch_encode_plus(*lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :int , *lowerCamelCase_ :Optional[Any] , **lowerCamelCase_ :Any ): """simple docstring""" lowerCamelCase__ : Optional[Any] =kwargs.get('is_split_into_words' , lowerCamelCase_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" ' pretokenized inputs.' ) return super()._encode_plus(*lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :Dict , lowerCamelCase_ :str , lowerCamelCase_ :Optional[str] = None ): """simple docstring""" lowerCamelCase__ : Optional[Any] =self._tokenizer.model.save(lowerCamelCase_ , name=lowerCamelCase_ ) return tuple(lowerCamelCase_ ) def UpperCAmelCase__ ( self :List[Any] , lowerCamelCase_ :"Conversation" ): """simple docstring""" lowerCamelCase__ : Optional[int] =[] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) + [self.eos_token_id] ) if len(lowerCamelCase_ ) > self.model_max_length: lowerCamelCase__ : List[str] =input_ids[-self.model_max_length :] return input_ids
126
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a__ ( unittest.TestCase ): '''simple docstring''' @property def __SCREAMING_SNAKE_CASE ( self ) -> Any: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __SCREAMING_SNAKE_CASE ( self ) -> int: lowerCAmelCase__ = self.dummy_uncond_unet lowerCAmelCase__ = PNDMScheduler() lowerCAmelCase__ = PNDMPipeline(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ ) pndm.to(lowerCamelCase_ ) pndm.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = pndm(generator=lowerCamelCase_ , num_inference_steps=20 , output_type='''numpy''' ).images lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = pndm(generator=lowerCamelCase_ , num_inference_steps=20 , output_type='''numpy''' , return_dict=lowerCamelCase_ )[0] lowerCAmelCase__ = image[0, -3:, -3:, -1] lowerCAmelCase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase__ = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class a__ ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self ) -> Tuple: lowerCAmelCase__ = '''google/ddpm-cifar10-32''' lowerCAmelCase__ = UNetaDModel.from_pretrained(lowerCamelCase_ ) lowerCAmelCase__ = PNDMScheduler() lowerCAmelCase__ = PNDMPipeline(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ ) pndm.to(lowerCamelCase_ ) pndm.set_progress_bar_config(disable=lowerCamelCase_ ) lowerCAmelCase__ = torch.manual_seed(0 ) lowerCAmelCase__ = pndm(generator=lowerCamelCase_ , output_type='''numpy''' ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase__ = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
228
'''simple docstring''' from collections.abc import Iterable from typing import Any class a__ : '''simple docstring''' def __init__( self , lowerCamelCase_ = None ) -> List[str]: lowerCAmelCase__ = value lowerCAmelCase__ = None # Added in order to delete a node easier lowerCAmelCase__ = None lowerCAmelCase__ = None def __repr__( self ) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class a__ : '''simple docstring''' def __init__( self , lowerCamelCase_ = None ) -> Union[str, Any]: lowerCAmelCase__ = root def __str__( self ) -> str: return str(self.root ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ ) -> None: if new_children is not None: # reset its kids lowerCAmelCase__ = node.parent if node.parent is not None: # reset its parent if self.is_right(lowerCamelCase_ ): # If it is the right children lowerCAmelCase__ = new_children else: lowerCAmelCase__ = new_children else: lowerCAmelCase__ = new_children def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> bool: if node.parent and node.parent.right: return node == node.parent.right return False def __SCREAMING_SNAKE_CASE ( self ) -> bool: return self.root is None def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> None: lowerCAmelCase__ = Node(lowerCamelCase_ ) # create a new Node if self.empty(): # if Tree is empty lowerCAmelCase__ = new_node # set its root else: # Tree is not empty lowerCAmelCase__ = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: lowerCAmelCase__ = new_node # We insert the new node in a leaf break else: lowerCAmelCase__ = parent_node.left else: if parent_node.right is None: lowerCAmelCase__ = new_node break else: lowerCAmelCase__ = parent_node.right lowerCAmelCase__ = parent_node def __SCREAMING_SNAKE_CASE ( self , *lowerCamelCase_ ) -> None: for value in values: self.__insert(lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Node | None: if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''' ) else: lowerCAmelCase__ = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: lowerCAmelCase__ = node.left if value < node.value else node.right return node def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ = None ) -> Node | None: if node is None: if self.root is None: return None lowerCAmelCase__ = self.root if not self.empty(): while node.right is not None: lowerCAmelCase__ = node.right return node def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ = None ) -> Node | None: if node is None: lowerCAmelCase__ = self.root if self.root is None: return None if not self.empty(): lowerCAmelCase__ = self.root while node.left is not None: lowerCAmelCase__ = node.left return node def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> None: lowerCAmelCase__ = self.search(lowerCamelCase_ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(lowerCamelCase_ , lowerCamelCase_ ) elif node.left is None: # Has only right children self.__reassign_nodes(lowerCamelCase_ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(lowerCamelCase_ , node.left ) else: lowerCAmelCase__ = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore lowerCAmelCase__ = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_=None ) -> Any: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ ) -> None: if node: self.inorder(lowerCamelCase_ , node.left ) arr.append(node.value ) self.inorder(lowerCamelCase_ , node.right ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ ) -> int: lowerCAmelCase__ = [] self.inorder(lowerCamelCase_ , lowerCamelCase_ ) # append all values to list using inorder traversal return arr[k - 1] def _snake_case ( A ) -> list[Node]: lowerCAmelCase__ = [] if curr_node is not None: lowerCAmelCase__ = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def _snake_case ( ) -> None: lowerCAmelCase__ = (8, 3, 6, 1, 10, 14, 13, 4, 7) lowerCAmelCase__ = BinarySearchTree() for i in testlist: t.insert(A ) # Prints all the elements of the list in order traversal print(A ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''' , t.get_max().value ) # type: ignore print('''Min Value: ''' , t.get_min().value ) # type: ignore for i in testlist: t.remove(A ) print(A ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
228
1
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase :Dict = logging.get_logger() @dataclass class _lowerCamelCase : '''simple docstring''' A_ : str = 42 A_ : Optional[Any] = field(default_factory=__UpperCamelCase ) A_ : List[str] = field(default_factory=__UpperCamelCase ) def __lowerCAmelCase ( self : List[str] , _A : Dict , _A : Tensor , _A : Tensor ) -> Optional[Any]: __magic_name__ : Dict = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : List[Any] , _A : Tensor ) -> Any: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowerCAmelCase ( self : Optional[int] ) -> str: return list(filter(lambda _A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _lowerCamelCase : '''simple docstring''' A_ : int = 42 A_ : Any = 42 A_ : List[str] = 0 A_ : Optional[Any] = field(default_factory=__UpperCamelCase ) A_ : Dict = field(default_factory=__UpperCamelCase ) def __call__( self : str , _A : Tensor ) -> Union[str, Any]: __magic_name__ : List[str] = Tracker(self.dest )(a_ ).parametrized __magic_name__ : Tuple = Tracker(self.src )(a_ ).parametrized __magic_name__ : int = list(filter(lambda _A : type(a_ ) not in self.src_skip , a_ ) ) __magic_name__ : str = list(filter(lambda _A : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ): raise Exception( F'Numbers of operations are different. Source module has {len(a_ )} operations while' F' destination module has {len(a_ )}.' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'Transfered from={src_m} to={dest_m}' ) def lowerCamelCase ( lowerCAmelCase : str , lowerCAmelCase : ResNetConfig , lowerCAmelCase : Path , lowerCAmelCase : bool = True ): """simple docstring""" print(f'Converting {name}...' ) with torch.no_grad(): __magic_name__ : Optional[Any] = timm.create_model(_UpperCAmelCase , pretrained=_UpperCAmelCase ).eval() __magic_name__ : int = ResNetForImageClassification(_UpperCAmelCase ).eval() __magic_name__ : List[Any] = ModuleTransfer(src=_UpperCAmelCase , dest=_UpperCAmelCase ) __magic_name__ : Union[str, Any] = torch.randn((1, 3, 224, 224) ) module_transfer(_UpperCAmelCase ) assert torch.allclose(from_model(_UpperCAmelCase ) , our_model(_UpperCAmelCase ).logits ), "The model logits don't match the original one." __magic_name__ : Optional[int] = f'resnet{"-".join(name.split("resnet" ) )}' print(_UpperCAmelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add model' , use_temp_dir=_UpperCAmelCase , ) # we can use the convnext one __magic_name__ : Optional[int] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add image processor' , use_temp_dir=_UpperCAmelCase , ) print(f'Pushed {checkpoint_name}' ) def lowerCamelCase ( lowerCAmelCase : Path , lowerCAmelCase : str = None , lowerCAmelCase : bool = True ): """simple docstring""" __magic_name__ : str = '''imagenet-1k-id2label.json''' __magic_name__ : int = 1000 __magic_name__ : Optional[int] = (1, num_labels) __magic_name__ : Any = '''huggingface/label-files''' __magic_name__ : Tuple = num_labels __magic_name__ : Tuple = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type='dataset' ) , 'r' ) ) __magic_name__ : str = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __magic_name__ : Any = idalabel __magic_name__ : str = {v: k for k, v in idalabel.items()} __magic_name__ : List[str] = partial(_UpperCAmelCase , num_labels=_UpperCAmelCase , idalabel=_UpperCAmelCase , labelaid=_UpperCAmelCase ) __magic_name__ : Any = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='basic' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='basic' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), } if model_name: convert_weight_and_push(_UpperCAmelCase , names_to_config[model_name] , _UpperCAmelCase , _UpperCAmelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return config, expected_shape if __name__ == "__main__": lowerCAmelCase :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) lowerCAmelCase :List[Any] = parser.parse_args() lowerCAmelCase :str = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
331
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def a ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[int] ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = k_size // 2 __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] __UpperCAmelCase : Any = 1 / (2 * pi * sigma) * exp(-(square(_UpperCAmelCase ) + square(_UpperCAmelCase )) / (2 * square(_UpperCAmelCase )) ) return g def a ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any] ): '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = image.shape[0], image.shape[1] # dst image height and width __UpperCAmelCase : str = height - k_size + 1 __UpperCAmelCase : Optional[int] = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows __UpperCAmelCase : str = zeros((dst_height * dst_width, k_size * k_size) ) __UpperCAmelCase : Optional[Any] = 0 for i, j in product(range(_UpperCAmelCase ) , range(_UpperCAmelCase ) ): __UpperCAmelCase : int = ravel(image[i : i + k_size, j : j + k_size] ) __UpperCAmelCase : Union[str, Any] = window row += 1 # turn the kernel into shape(k*k, 1) __UpperCAmelCase : Tuple = gen_gaussian_kernel(_UpperCAmelCase , _UpperCAmelCase ) __UpperCAmelCase : List[Any] = ravel(_UpperCAmelCase ) # reshape and get the dst image __UpperCAmelCase : Optional[Any] = dot(_UpperCAmelCase , _UpperCAmelCase ).reshape(_UpperCAmelCase , _UpperCAmelCase ).astype(_UpperCAmelCase ) return dst if __name__ == "__main__": # read original image __A =imread(R"../image_data/lena.jpg") # turn image in gray scale value __A =cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size __A =gaussian_filter(gray, 3, sigma=1) __A =gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussianaxa) imshow("gaussian filter with 5x5 mask", gaussianaxa) waitKey()
226
0
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowercase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str, lowerCamelCase : bool, lowerCamelCase : Optional[int] = None, lowerCamelCase : Optional[int] = None )-> Any: super().__init__() lowerCamelCase__ : Optional[int] =learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" lowerCamelCase__ : Tuple =torch.zeros(lowerCamelCase, lowerCamelCase ) else: lowerCamelCase__ : List[str] =None lowerCamelCase__ : str =torch.nn.Parameter(lowerCamelCase ) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' _a = 42 _a = 42 _a = 42 _a = 42 _a = 42 _a = 42 def __init__( self : List[str], lowerCamelCase : VQModel, lowerCamelCase : CLIPTextModel, lowerCamelCase : CLIPTokenizer, lowerCamelCase : TransformeraDModel, lowerCamelCase : VQDiffusionScheduler, lowerCamelCase : LearnedClassifierFreeSamplingEmbeddings, )-> List[str]: super().__init__() self.register_modules( vqvae=lowerCamelCase, transformer=lowerCamelCase, text_encoder=lowerCamelCase, tokenizer=lowerCamelCase, scheduler=lowerCamelCase, learned_classifier_free_sampling_embeddings=lowerCamelCase, ) def snake_case ( self : List[str], lowerCamelCase : List[Any], lowerCamelCase : Dict, lowerCamelCase : List[Any] )-> int: lowerCamelCase__ : Optional[int] =len(lowerCamelCase ) if isinstance(lowerCamelCase, lowerCamelCase ) else 1 # get prompt text embeddings lowerCamelCase__ : Tuple =self.tokenizer( lowerCamelCase, padding='''max_length''', max_length=self.tokenizer.model_max_length, return_tensors='''pt''', ) lowerCamelCase__ : Any =text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase__ : List[Any] =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase__ : List[str] =text_input_ids[:, : self.tokenizer.model_max_length] lowerCamelCase__ : Tuple =self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 lowerCamelCase__ : Any =prompt_embeds / prompt_embeds.norm(dim=-1, keepdim=lowerCamelCase ) # duplicate text embeddings for each generation per prompt lowerCamelCase__ : Dict =prompt_embeds.repeat_interleave(lowerCamelCase, dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: lowerCamelCase__ : Dict =self.learned_classifier_free_sampling_embeddings.embeddings lowerCamelCase__ : Union[str, Any] =negative_prompt_embeds.unsqueeze(0 ).repeat(lowerCamelCase, 1, 1 ) else: lowerCamelCase__ : Optional[Any] =[''''''] * batch_size lowerCamelCase__ : Union[str, Any] =text_input_ids.shape[-1] lowerCamelCase__ : List[str] =self.tokenizer( lowerCamelCase, padding='''max_length''', max_length=lowerCamelCase, truncation=lowerCamelCase, return_tensors='''pt''', ) lowerCamelCase__ : Optional[int] =self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings lowerCamelCase__ : List[Any] =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1, keepdim=lowerCamelCase ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase__ : int =negative_prompt_embeds.shape[1] lowerCamelCase__ : Optional[Any] =negative_prompt_embeds.repeat(1, lowerCamelCase, 1 ) lowerCamelCase__ : int =negative_prompt_embeds.view(batch_size * num_images_per_prompt, lowerCamelCase, -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase__ : Union[str, Any] =torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : str, lowerCamelCase : Union[str, List[str]], lowerCamelCase : int = 100, lowerCamelCase : float = 5.0, lowerCamelCase : float = 1.0, lowerCamelCase : int = 1, lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None, lowerCamelCase : Optional[torch.FloatTensor] = None, lowerCamelCase : Optional[str] = "pil", lowerCamelCase : bool = True, lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None, lowerCamelCase : int = 1, )-> Union[ImagePipelineOutput, Tuple]: if isinstance(lowerCamelCase, lowerCamelCase ): lowerCamelCase__ : Union[str, Any] =1 elif isinstance(lowerCamelCase, lowerCamelCase ): lowerCamelCase__ : List[Any] =len(lowerCamelCase ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase )}''' ) lowerCamelCase__ : Tuple =batch_size * num_images_per_prompt lowerCamelCase__ : Optional[Any] =guidance_scale > 1.0 lowerCamelCase__ : Dict =self._encode_prompt(lowerCamelCase, lowerCamelCase, lowerCamelCase ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(lowerCamelCase, lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(lowerCamelCase )}.''' ) # get the initial completely masked latents unless the user supplied it lowerCamelCase__ : Any =(batch_size, self.transformer.num_latent_pixels) if latents is None: lowerCamelCase__ : Union[str, Any] =self.transformer.num_vector_embeds - 1 lowerCamelCase__ : Optional[Any] =torch.full(lowerCamelCase, lowerCamelCase ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,''' F''' {self.transformer.num_vector_embeds - 1} (inclusive).''' ) lowerCamelCase__ : List[Any] =latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(lowerCamelCase, device=self.device ) lowerCamelCase__ : Optional[int] =self.scheduler.timesteps.to(self.device ) lowerCamelCase__ : int =latents for i, t in enumerate(self.progress_bar(lowerCamelCase ) ): # expand the sample if we are doing classifier free guidance lowerCamelCase__ : Dict =torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` lowerCamelCase__ : Optional[int] =self.transformer(lowerCamelCase, encoder_hidden_states=lowerCamelCase, timestep=lowerCamelCase ).sample if do_classifier_free_guidance: lowerCamelCase__ , lowerCamelCase__ : str =model_output.chunk(2 ) lowerCamelCase__ : Any =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(lowerCamelCase, dim=1, keepdim=lowerCamelCase ) lowerCamelCase__ : str =self.truncate(lowerCamelCase, lowerCamelCase ) # remove `log(0)`'s (`-inf`s) lowerCamelCase__ : Dict =model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase__ : List[str] =self.scheduler.step(lowerCamelCase, timestep=lowerCamelCase, sample=lowerCamelCase, generator=lowerCamelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowerCamelCase, lowerCamelCase, lowerCamelCase ) lowerCamelCase__ : Any =self.vqvae.config.vq_embed_dim lowerCamelCase__ : int =(batch_size, self.transformer.height, self.transformer.width, embedding_channels) lowerCamelCase__ : Tuple =self.vqvae.quantize.get_codebook_entry(lowerCamelCase, shape=lowerCamelCase ) lowerCamelCase__ : str =self.vqvae.decode(lowerCamelCase, force_not_quantize=lowerCamelCase ).sample lowerCamelCase__ : Optional[Any] =(image / 2 + 0.5).clamp(0, 1 ) lowerCamelCase__ : Dict =image.cpu().permute(0, 2, 3, 1 ).numpy() if output_type == "pil": lowerCamelCase__ : Dict =self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase ) def snake_case ( self : List[Any], lowerCamelCase : torch.FloatTensor, lowerCamelCase : float )-> torch.FloatTensor: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] =torch.sort(lowerCamelCase, 1, descending=lowerCamelCase ) lowerCamelCase__ : Optional[Any] =torch.exp(lowerCamelCase ) lowerCamelCase__ : Optional[Any] =sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out lowerCamelCase__ : int =torch.full_like(keep_mask[:, 0:1, :], lowerCamelCase ) lowerCamelCase__ : Any =torch.cat((all_true, keep_mask), dim=1 ) lowerCamelCase__ : str =keep_mask[:, :-1, :] lowerCamelCase__ : List[str] =keep_mask.gather(1, indices.argsort(1 ) ) lowerCamelCase__ : Optional[int] =log_p_x_0.clone() lowerCamelCase__ : Union[str, Any] =-torch.inf # -inf = log(0) return rv
272
"""simple docstring""" from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Dict, lowerCamelCase : str, lowerCamelCase : Dict=13, lowerCamelCase : Optional[Any]=7, lowerCamelCase : List[Any]=True, lowerCamelCase : Dict=True, lowerCamelCase : List[Any]=True, lowerCamelCase : Optional[int]=True, lowerCamelCase : int=99, lowerCamelCase : Optional[int]=[1, 1, 2], lowerCamelCase : str=1, lowerCamelCase : List[Any]=32, lowerCamelCase : str=4, lowerCamelCase : Dict=8, lowerCamelCase : List[Any]=37, lowerCamelCase : Optional[int]="gelu_new", lowerCamelCase : Union[str, Any]=0.1, lowerCamelCase : List[Any]=0.1, lowerCamelCase : List[Any]=0.0, lowerCamelCase : Dict=512, lowerCamelCase : Dict=3, lowerCamelCase : str=0.02, lowerCamelCase : str=3, lowerCamelCase : Optional[int]=4, lowerCamelCase : List[str]=None, lowerCamelCase : Tuple=False, )-> Union[str, Any]: lowerCamelCase__ : int =parent lowerCamelCase__ : Dict =batch_size lowerCamelCase__ : Dict =seq_length lowerCamelCase__ : Any =is_training lowerCamelCase__ : int =use_input_mask lowerCamelCase__ : Tuple =use_token_type_ids lowerCamelCase__ : int =use_labels lowerCamelCase__ : Tuple =vocab_size lowerCamelCase__ : Union[str, Any] =block_sizes lowerCamelCase__ : Any =num_decoder_layers lowerCamelCase__ : Optional[Any] =d_model lowerCamelCase__ : List[str] =n_head lowerCamelCase__ : List[Any] =d_head lowerCamelCase__ : Dict =d_inner lowerCamelCase__ : Dict =hidden_act lowerCamelCase__ : List[str] =hidden_dropout lowerCamelCase__ : Union[str, Any] =attention_dropout lowerCamelCase__ : Union[str, Any] =activation_dropout lowerCamelCase__ : Dict =max_position_embeddings lowerCamelCase__ : Dict =type_vocab_size lowerCamelCase__ : Union[str, Any] =2 lowerCamelCase__ : Optional[int] =num_labels lowerCamelCase__ : List[str] =num_choices lowerCamelCase__ : Tuple =scope lowerCamelCase__ : Optional[int] =initializer_std # Used in the tests to check the size of the first attention layer lowerCamelCase__ : List[str] =n_head # Used in the tests to check the size of the first hidden state lowerCamelCase__ : Tuple =self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCamelCase__ : List[Any] =sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCamelCase__ : Union[str, Any] =self.num_hidden_layers + 2 def snake_case ( self : int )-> List[Any]: lowerCamelCase__ : Dict =ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) lowerCamelCase__ : Union[str, Any] =None if self.use_input_mask: lowerCamelCase__ : Any =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : int =None if self.use_token_type_ids: lowerCamelCase__ : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) lowerCamelCase__ : List[str] =None lowerCamelCase__ : Union[str, Any] =None lowerCamelCase__ : List[str] =None if self.use_labels: lowerCamelCase__ : List[Any] =ids_tensor([self.batch_size], self.type_sequence_label_size ) lowerCamelCase__ : Optional[Any] =ids_tensor([self.batch_size, self.seq_length], self.num_labels ) lowerCamelCase__ : Union[str, Any] =ids_tensor([self.batch_size], self.num_choices ) lowerCamelCase__ : Optional[int] =FunnelConfig( vocab_size=self.vocab_size, block_sizes=self.block_sizes, num_decoder_layers=self.num_decoder_layers, d_model=self.d_model, n_head=self.n_head, d_head=self.d_head, d_inner=self.d_inner, hidden_act=self.hidden_act, hidden_dropout=self.hidden_dropout, attention_dropout=self.attention_dropout, activation_dropout=self.activation_dropout, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_std=self.initializer_std, ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def snake_case ( self : List[Any], lowerCamelCase : Optional[Any], lowerCamelCase : Optional[int], lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : str, lowerCamelCase : List[str], lowerCamelCase : Dict, )-> Union[str, Any]: lowerCamelCase__ : Tuple =TFFunnelModel(config=lowerCamelCase ) lowerCamelCase__ : Dict ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : Tuple =model(lowerCamelCase ) lowerCamelCase__ : Optional[Any] =[input_ids, input_mask] lowerCamelCase__ : List[Any] =model(lowerCamelCase ) lowerCamelCase__ : Any =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model) ) lowerCamelCase__ : int =False lowerCamelCase__ : Any =TFFunnelModel(config=lowerCamelCase ) lowerCamelCase__ : str =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model) ) lowerCamelCase__ : Dict =False lowerCamelCase__ : Optional[int] =TFFunnelModel(config=lowerCamelCase ) lowerCamelCase__ : Tuple =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model) ) def snake_case ( self : Tuple, lowerCamelCase : List[Any], lowerCamelCase : Union[str, Any], lowerCamelCase : Union[str, Any], lowerCamelCase : str, lowerCamelCase : Optional[Any], lowerCamelCase : Tuple, lowerCamelCase : Dict, )-> Optional[Any]: lowerCamelCase__ : List[str] =TFFunnelBaseModel(config=lowerCamelCase ) lowerCamelCase__ : str ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : Union[str, Any] =model(lowerCamelCase ) lowerCamelCase__ : Tuple =[input_ids, input_mask] lowerCamelCase__ : Any =model(lowerCamelCase ) lowerCamelCase__ : Optional[Any] =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model) ) lowerCamelCase__ : List[Any] =False lowerCamelCase__ : Dict =TFFunnelBaseModel(config=lowerCamelCase ) lowerCamelCase__ : int =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 3, self.d_model) ) lowerCamelCase__ : Union[str, Any] =False lowerCamelCase__ : Optional[Any] =TFFunnelBaseModel(config=lowerCamelCase ) lowerCamelCase__ : str =model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model) ) def snake_case ( self : str, lowerCamelCase : Dict, lowerCamelCase : Dict, lowerCamelCase : List[Any], lowerCamelCase : Dict, lowerCamelCase : List[Any], lowerCamelCase : Union[str, Any], lowerCamelCase : List[Any], )-> List[Any]: lowerCamelCase__ : List[str] =TFFunnelForPreTraining(config=lowerCamelCase ) lowerCamelCase__ : List[Any] ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : Union[str, Any] =model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length) ) def snake_case ( self : str, lowerCamelCase : Tuple, lowerCamelCase : str, lowerCamelCase : List[Any], lowerCamelCase : List[Any], lowerCamelCase : str, lowerCamelCase : Tuple, lowerCamelCase : int, )-> List[Any]: lowerCamelCase__ : Union[str, Any] =TFFunnelForMaskedLM(config=lowerCamelCase ) lowerCamelCase__ : Tuple ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : List[Any] =model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case ( self : Optional[int], lowerCamelCase : Tuple, lowerCamelCase : Any, lowerCamelCase : List[str], lowerCamelCase : Union[str, Any], lowerCamelCase : str, lowerCamelCase : Optional[int], lowerCamelCase : Dict, )-> Union[str, Any]: lowerCamelCase__ : Optional[Any] =self.num_labels lowerCamelCase__ : Tuple =TFFunnelForSequenceClassification(config=lowerCamelCase ) lowerCamelCase__ : Tuple ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : List[str] =model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def snake_case ( self : Union[str, Any], lowerCamelCase : str, lowerCamelCase : Dict, lowerCamelCase : Dict, lowerCamelCase : Dict, lowerCamelCase : Optional[Any], lowerCamelCase : int, lowerCamelCase : Tuple, )-> int: lowerCamelCase__ : int =self.num_choices lowerCamelCase__ : List[Any] =TFFunnelForMultipleChoice(config=lowerCamelCase ) lowerCamelCase__ : int =tf.tile(tf.expand_dims(lowerCamelCase, 1 ), (1, self.num_choices, 1) ) lowerCamelCase__ : Union[str, Any] =tf.tile(tf.expand_dims(lowerCamelCase, 1 ), (1, self.num_choices, 1) ) lowerCamelCase__ : Optional[Any] =tf.tile(tf.expand_dims(lowerCamelCase, 1 ), (1, self.num_choices, 1) ) lowerCamelCase__ : Union[str, Any] ={ '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } lowerCamelCase__ : str =model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices) ) def snake_case ( self : str, lowerCamelCase : Dict, lowerCamelCase : Optional[Any], lowerCamelCase : Any, lowerCamelCase : str, lowerCamelCase : Union[str, Any], lowerCamelCase : Union[str, Any], lowerCamelCase : Dict, )-> Optional[int]: lowerCamelCase__ : Optional[Any] =self.num_labels lowerCamelCase__ : Optional[Any] =TFFunnelForTokenClassification(config=lowerCamelCase ) lowerCamelCase__ : Tuple ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : Union[str, Any] =model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def snake_case ( self : Optional[int], lowerCamelCase : Dict, lowerCamelCase : str, lowerCamelCase : Union[str, Any], lowerCamelCase : Union[str, Any], lowerCamelCase : Union[str, Any], lowerCamelCase : str, lowerCamelCase : Optional[int], )-> Tuple: lowerCamelCase__ : Tuple =TFFunnelForQuestionAnswering(config=lowerCamelCase ) lowerCamelCase__ : Union[str, Any] ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCamelCase__ : Optional[int] =model(lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def snake_case ( self : int )-> List[str]: lowerCamelCase__ : List[Any] =self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Tuple =config_and_inputs lowerCamelCase__ : str ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' _a = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) _a = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) _a = False _a = False def snake_case ( self : str )-> Tuple: lowerCamelCase__ : Any =TFFunnelModelTester(self ) lowerCamelCase__ : Any =ConfigTester(self, config_class=lowerCamelCase ) def snake_case ( self : List[str] )-> Tuple: self.config_tester.run_common_tests() def snake_case ( self : str )-> List[Any]: lowerCamelCase__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def snake_case ( self : str )-> Dict: lowerCamelCase__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowerCamelCase ) def snake_case ( self : int )-> List[Any]: lowerCamelCase__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase ) def snake_case ( self : Dict )-> Any: lowerCamelCase__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase ) def snake_case ( self : Tuple )-> Optional[Any]: lowerCamelCase__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase ) @require_tf class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' _a = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) _a = False _a = False def snake_case ( self : int )-> Tuple: lowerCamelCase__ : Union[str, Any] =TFFunnelModelTester(self, base=lowerCamelCase ) lowerCamelCase__ : Tuple =ConfigTester(self, config_class=lowerCamelCase ) def snake_case ( self : Any )-> Any: self.config_tester.run_common_tests() def snake_case ( self : Optional[Any] )-> Optional[Any]: lowerCamelCase__ : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*lowerCamelCase ) def snake_case ( self : Union[str, Any] )-> int: lowerCamelCase__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase ) def snake_case ( self : List[str] )-> Optional[int]: lowerCamelCase__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase )
272
1
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class _lowercase : '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int = 13 , SCREAMING_SNAKE_CASE__ : int = 64 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = 1_28 , SCREAMING_SNAKE_CASE__ : int=[16, 32, 64, 1_28] , SCREAMING_SNAKE_CASE__ : int = 7 , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 37 , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 1_28 , SCREAMING_SNAKE_CASE__ : List[int] = [2, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , ) -> Any: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = encoder_stride __lowerCAmelCase = num_attention_outputs __lowerCAmelCase = embed_dim __lowerCAmelCase = embed_dim + 1 __lowerCAmelCase = resolution __lowerCAmelCase = depths __lowerCAmelCase = hidden_sizes __lowerCAmelCase = dim __lowerCAmelCase = mlp_expansion_ratio def a ( self : Union[str, Any] ) -> List[Any]: __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def a ( self : Union[str, Any] ) -> Optional[Any]: return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Any: __lowerCAmelCase = TFEfficientFormerModel(config=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a ( self : Union[str, Any] ) -> int: __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs __lowerCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class _lowercase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' _SCREAMING_SNAKE_CASE : str = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE : Tuple = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def a ( self : Optional[int] ) -> Tuple: __lowerCAmelCase = TFEfficientFormerModelTester(self ) __lowerCAmelCase = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def a ( self : str ) -> List[str]: pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def a ( self : int ) -> Tuple: pass def a ( self : int ) -> str: __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> List[Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ): __lowerCAmelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCAmelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) if hasattr(self.model_tester , """encoder_seq_length""" ): __lowerCAmelCase = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __lowerCAmelCase = seq_length * self.model_tester.chunk_length else: __lowerCAmelCase = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __lowerCAmelCase = outputs.decoder_hidden_states self.asseretIsInstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = getattr(self.model_tester , """seq_length""" , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = getattr(self.model_tester , """decoder_seq_length""" , SCREAMING_SNAKE_CASE__ ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCAmelCase = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False ) -> List[Any]: __lowerCAmelCase = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def a ( self : str ) -> Optional[Any]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def a ( self : List[str] ) -> Optional[Any]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> List[Any]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : List[Any] ) -> List[str]: for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = TFEfficientFormerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> int: __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True __lowerCAmelCase = getattr(self.model_tester , """seq_length""" , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = getattr(self.model_tester , """encoder_seq_length""" , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = getattr(self.model_tester , """key_length""" , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = getattr(self.model_tester , """chunk_length""" , SCREAMING_SNAKE_CASE__ ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __lowerCAmelCase = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __lowerCAmelCase = True __lowerCAmelCase = False __lowerCAmelCase = True __lowerCAmelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __lowerCAmelCase = True __lowerCAmelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def a ( self : Dict ) -> List[Any]: # We use a simplified version of this test for EfficientFormer because it requires training=False # and Keras refuses to let us force that during functional construction __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __lowerCAmelCase = model_class(SCREAMING_SNAKE_CASE__ ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __lowerCAmelCase = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=SCREAMING_SNAKE_CASE__ ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ ) self.assertTrue(outputs_dict is not None ) def UpperCamelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class _lowercase ( unittest.TestCase ): '''simple docstring''' @cached_property def a ( self : Any ) -> Any: return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> Any: __lowerCAmelCase = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""tf""" ) # forward pass __lowerCAmelCase = model(**SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) # verify the logits __lowerCAmelCase = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = tf.constant([-0.0_5_5_5, 0.4_8_2_5, -0.0_8_5_2] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Tuple ) -> Dict: __lowerCAmelCase = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""tf""" ) # forward pass __lowerCAmelCase = model(**SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) # verify the logits __lowerCAmelCase = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = tf.constant([-0.1_3_1_2, 0.4_3_5_3, -1.0_4_9_9] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
229
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class _lowercase : '''simple docstring''' _SCREAMING_SNAKE_CASE : float _SCREAMING_SNAKE_CASE : TreeNode | None = None _SCREAMING_SNAKE_CASE : TreeNode | None = None def UpperCamelCase_ ( snake_case_ : TreeNode | None ) -> bool: '''simple docstring''' def is_valid_tree(snake_case_ : TreeNode | None ) -> bool: if node is None: return True if not isinstance(snake_case_ , snake_case_ ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(snake_case_ ): raise ValueError( """Each node should be type of TreeNode and data should be float.""" ) def is_binary_search_tree_recursive_check( snake_case_ : TreeNode | None , snake_case_ : float , snake_case_ : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , snake_case_ , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , snake_case_ ) ) return is_binary_search_tree_recursive_check(snake_case_ , -float("""inf""" ) , float("""inf""" ) ) if __name__ == "__main__": import doctest doctest.testmod()
229
1
"""simple docstring""" from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class _lowercase ( __a ): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] , UpperCamelCase__ : float ) -> float: '''simple docstring''' return 0.0 def lowerCAmelCase (__UpperCamelCase : np.ndarray , __UpperCamelCase : int ): """simple docstring""" __UpperCamelCase =min([-2_0, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([2_0, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def lowerCAmelCase (__UpperCamelCase : FilterType , __UpperCamelCase : int ): """simple docstring""" __UpperCamelCase =5_1_2 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(__UpperCamelCase ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(__UpperCamelCase ) ) __UpperCamelCase =2_0 * np.logaa(__UpperCamelCase ) # 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 __UpperCamelCase =get_bounds(__UpperCamelCase , __UpperCamelCase ) plt.ylim(max([-8_0, bounds[0]] ) , min([8_0, bounds[1]] ) ) plt.ylabel('''Gain (dB)''' ) plt.plot(__UpperCamelCase ) plt.show() def lowerCAmelCase (__UpperCamelCase : FilterType , __UpperCamelCase : int ): """simple docstring""" __UpperCamelCase =5_1_2 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(__UpperCamelCase ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(__UpperCamelCase ) ) # 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(__UpperCamelCase , -2 * pi ) ) plt.show()
85
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase = {'''configuration_ibert''': ['''IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''IBertConfig''', '''IBertOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''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 __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
85
1
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __a = ( "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) ) __a = ( ("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"), ) __a = ( ("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), ) __a = ( ("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), ) __a = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) __a = ( ("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), ) __a = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def A_ ( ): '''simple docstring''' snake_case_, snake_case_ :Tuple = randrange(len(_lowercase ) ), randrange(len(_lowercase ) ) snake_case_ :Optional[Any] = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] snake_case_, snake_case_ :List[str] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def A_ ( _lowercase = 100 ): '''simple docstring''' return (generate_random_hand() for _ in range(_lowercase )) @pytest.mark.parametrize("""hand, expected""", _lowercase ) def A_ ( _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""", _lowercase ) def A_ ( _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""", _lowercase ) def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' snake_case_ :Union[str, Any] = PokerHand(_lowercase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""", _lowercase ) def A_ ( _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""", _lowercase ) def A_ ( _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""", _lowercase ) def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase ).compare_with(PokerHand(_lowercase ) ) == expected @pytest.mark.parametrize("""hand, other, expected""", generate_random_hands() ) def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' assert PokerHand(_lowercase ).compare_with(PokerHand(_lowercase ) ) == expected def A_ ( ): '''simple docstring''' snake_case_ :Any = [PokerHand(_lowercase ) for hand in SORTED_HANDS] snake_case_ :Optional[Any] = poker_hands.copy() shuffle(_lowercase ) snake_case_ :Optional[int] = chain(sorted(_lowercase ) ) for index, hand in enumerate(_lowercase ): assert hand == poker_hands[index] def A_ ( ): '''simple docstring''' snake_case_ :Any = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=_lowercase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def A_ ( ): '''simple docstring''' snake_case_ :Any = PokerHand("""2C 4S AS 3D 5C""" ) snake_case_ :Optional[int] = True snake_case_ :Optional[Any] = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def A_ ( ): '''simple docstring''' snake_case_ :Any = 0 snake_case_ :int = os.path.abspath(os.path.dirname(_lowercase ) ) snake_case_ :Optional[int] = os.path.join(_lowercase, """poker_hands.txt""" ) with open(_lowercase ) as file_hand: for line in file_hand: snake_case_ :Any = line[:14].strip() snake_case_ :Union[str, Any] = line[15:].strip() snake_case_, snake_case_ :Tuple = PokerHand(_lowercase ), PokerHand(_lowercase ) snake_case_ :List[str] = player.compare_with(_lowercase ) if output == "Win": answer += 1 assert answer == 376
66
"""simple docstring""" import math class lowerCamelCase : '''simple docstring''' def lowerCAmelCase_ ( self: Tuple , snake_case: list[list[float]] , snake_case: list[int] ) -> int: snake_case_ :Any = 0.0 snake_case_ :Tuple = 0.0 for i in range(len(snake_case ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def lowerCAmelCase_ ( self: Optional[int] , snake_case: list[list[int | float]] , snake_case: list[int] , snake_case: int , snake_case: float ) -> list[list[int | float]]: for i in range(len(snake_case ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def A_ ( ): '''simple docstring''' snake_case_ :Dict = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) snake_case_ :List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training snake_case_ :Optional[Any] = SelfOrganizingMap() snake_case_ :Dict = 3 snake_case_ :Dict = 0.5 for _ in range(_lowercase ): for j in range(len(_lowercase ) ): # training sample snake_case_ :List[Any] = training_samples[j] # Compute the winning vector snake_case_ :Optional[int] = self_organizing_map.get_winner(_lowercase, _lowercase ) # Update the winning vector snake_case_ :List[str] = self_organizing_map.update(_lowercase, _lowercase, _lowercase, _lowercase ) # classify test sample snake_case_ :str = [0, 0, 0, 1] snake_case_ :List[Any] = self_organizing_map.get_winner(_lowercase, _lowercase ) # results print(f"""Clusters that the test sample belongs to : {winner}""" ) print(f"""Weights that have been trained : {weights}""" ) # running the main() function if __name__ == "__main__": main()
66
1
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = None class lowerCamelCase (__lowerCamelCase , __lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = 2 @register_to_config def __init__( self : Optional[Any], _UpperCAmelCase : float = 0.02, _UpperCAmelCase : float = 1_0_0, _UpperCAmelCase : float = 1.007, _UpperCAmelCase : float = 8_0, _UpperCAmelCase : float = 0.05, _UpperCAmelCase : float = 5_0, ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = sigma_max # setable values SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : np.IntTensor = None SCREAMING_SNAKE_CASE__ : torch.FloatTensor = None # sigma(t_i) def A_ ( self : Optional[Any], _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : Optional[int] = None ) -> torch.FloatTensor: """simple docstring""" return sample def A_ ( self : Tuple, _UpperCAmelCase : int, _UpperCAmelCase : Union[str, torch.device] = None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_inference_steps SCREAMING_SNAKE_CASE__ : int = np.arange(0, self.num_inference_steps )[::-1].copy() SCREAMING_SNAKE_CASE__ : str = torch.from_numpy(_UpperCAmelCase ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor(_UpperCAmelCase, dtype=torch.floataa, device=_UpperCAmelCase ) def A_ ( self : Any, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : float, _UpperCAmelCase : Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: SCREAMING_SNAKE_CASE__ : List[Any] = min(self.config.s_churn / self.num_inference_steps, 2**0.5 - 1 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # sample eps ~ N(0, S_noise^2 * I) SCREAMING_SNAKE_CASE__ : Optional[int] = self.config.s_noise * randn_tensor(sample.shape, generator=_UpperCAmelCase ).to(sample.device ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sigma + gamma * sigma SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def A_ ( self : Optional[int], _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : float, _UpperCAmelCase : float, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : bool = True, ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = sample_hat + sigma_hat * model_output SCREAMING_SNAKE_CASE__ : Dict = (sample_hat - pred_original_sample) / sigma_hat SCREAMING_SNAKE_CASE__ : List[Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_UpperCAmelCase, derivative=_UpperCAmelCase, pred_original_sample=_UpperCAmelCase ) def A_ ( self : Tuple, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : float, _UpperCAmelCase : float, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : torch.FloatTensor, _UpperCAmelCase : bool = True, ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = sample_prev + sigma_prev * model_output SCREAMING_SNAKE_CASE__ : Optional[Any] = (sample_prev - pred_original_sample) / sigma_prev SCREAMING_SNAKE_CASE__ : str = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_UpperCAmelCase, derivative=_UpperCAmelCase, pred_original_sample=_UpperCAmelCase ) def A_ ( self : Optional[Any], _UpperCAmelCase : int, _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int] ) -> str: """simple docstring""" raise NotImplementedError()
354
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def _a ( SCREAMING_SNAKE_CASE__ : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Dict = analyze_text(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = list(" " + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE__ : str = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE__ : str = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE__ : Optional[int] = single_char_strings[ch] SCREAMING_SNAKE_CASE__ : Any = my_str / all_sum my_fir_sum += prob * math.loga(SCREAMING_SNAKE_CASE__ ) # entropy formula. # print entropy print(f'''{round(-1 * my_fir_sum ):.1f}''' ) # two len string SCREAMING_SNAKE_CASE__ : Union[str, Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE__ : int = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE__ : List[str] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE__ : Optional[Any] = two_char_strings[sequence] SCREAMING_SNAKE_CASE__ : Tuple = int(SCREAMING_SNAKE_CASE__ ) / all_sum my_sec_sum += prob * math.loga(SCREAMING_SNAKE_CASE__ ) # print second entropy print(f'''{round(-1 * my_sec_sum ):.1f}''' ) # print the difference between them print(f'''{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}''' ) def _a ( SCREAMING_SNAKE_CASE__ : str ) -> tuple[dict, dict]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = Counter() # type: ignore SCREAMING_SNAKE_CASE__ : Dict = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def _a ( ) -> str: '''simple docstring''' import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
191
0
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Tuple = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[int] = ReformerTokenizer _UpperCamelCase : Tuple = ReformerTokenizerFast _UpperCamelCase : Tuple = True _UpperCamelCase : int = False _UpperCamelCase : Union[str, Any] = True def __A ( self ): super().setUp() _lowerCAmelCase : Any = ReformerTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : Optional[int] = """<s>""" _lowerCAmelCase : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __A ( self ): _lowerCAmelCase : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(a__ ) , 1000 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : Any = self.get_tokenizer() _lowerCAmelCase : Dict = self.get_rust_tokenizer() _lowerCAmelCase : Any = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : Any = tokenizer.tokenize(a__ ) _lowerCAmelCase : Dict = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() _lowerCAmelCase : str = tokenizer.encode(a__ ) _lowerCAmelCase : Dict = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) def __A ( self , a__=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): _lowerCAmelCase : Any = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) # Simple input _lowerCAmelCase : List[str] = """This is a simple input""" _lowerCAmelCase : Optional[int] = ["""This is a simple input 1""", """This is a simple input 2"""] _lowerCAmelCase : List[Any] = ("""This is a simple input""", """This is a pair""") _lowerCAmelCase : Optional[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(a__ , tokenizer_r.encode , a__ , max_length=a__ , padding="""max_length""" ) # Simple input self.assertRaises(a__ , tokenizer_r.encode_plus , a__ , max_length=a__ , padding="""max_length""" ) # Simple input self.assertRaises( a__ , tokenizer_r.batch_encode_plus , a__ , max_length=a__ , padding="""max_length""" , ) # Pair input self.assertRaises(a__ , tokenizer_r.encode , a__ , max_length=a__ , padding="""max_length""" ) # Pair input self.assertRaises(a__ , tokenizer_r.encode_plus , a__ , max_length=a__ , padding="""max_length""" ) # Pair input self.assertRaises( a__ , tokenizer_r.batch_encode_plus , a__ , max_length=a__ , padding="""max_length""" , ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase : Optional[Any] = ReformerTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Any = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [285, 46, 10, 170, 382] , ) _lowerCAmelCase : List[str] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : Tuple = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _lowerCAmelCase : List[str] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def __A ( self ): _lowerCAmelCase : Union[str, Any] = """Hello World!""" _lowerCAmelCase : Tuple = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Dict = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) _lowerCAmelCase : Union[str, Any] = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @require_torch @slow def __A ( self ): import torch from transformers import ReformerConfig, ReformerModel # Build sequence _lowerCAmelCase : Union[str, Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] _lowerCAmelCase : Dict = """ """.join(a__ ) _lowerCAmelCase : List[str] = self.big_tokenizer.encode_plus(a__ , return_tensors="""pt""" ) _lowerCAmelCase : Optional[int] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) _lowerCAmelCase : List[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) _lowerCAmelCase : Optional[int] = encoded_sequence["""input_ids"""].shape _lowerCAmelCase : Any = ReformerModel(a__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**a__ ) model(**a__ ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : Dict = {"""input_ids""": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 _lowerCAmelCase : str = [ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=a__ , sequences=a__ , )
44
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
1
"""simple docstring""" import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __A : Optional[Any] = 4 __A : Dict = 3 class _a ( lowerCAmelCase): """simple docstring""" pass def lowercase ( _SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' for shard in shards: for i in range(_SCREAMING_SNAKE_CASE ): yield {"i": i, "shard": shard} def lowercase ( ): '''simple docstring''' _UpperCAmelCase = int(os.environ['''RANK'''] ) _UpperCAmelCase = int(os.environ['''WORLD_SIZE'''] ) _UpperCAmelCase = ArgumentParser() parser.add_argument('''--streaming''' , type=_SCREAMING_SNAKE_CASE ) parser.add_argument('''--local_rank''' , type=_SCREAMING_SNAKE_CASE ) parser.add_argument('''--num_workers''' , type=_SCREAMING_SNAKE_CASE , default=0 ) _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = args.streaming _UpperCAmelCase = args.num_workers _UpperCAmelCase = {'''shards''': [f'shard_{shard_idx}' for shard_idx in range(_SCREAMING_SNAKE_CASE )]} _UpperCAmelCase = IterableDataset.from_generator(_SCREAMING_SNAKE_CASE , gen_kwargs=_SCREAMING_SNAKE_CASE ) if not streaming: _UpperCAmelCase = Dataset.from_list(list(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = split_dataset_by_node(_SCREAMING_SNAKE_CASE , rank=_SCREAMING_SNAKE_CASE , world_size=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.utils.data.DataLoader(_SCREAMING_SNAKE_CASE , num_workers=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = NUM_SHARDS * NUM_ITEMS_PER_SHARD _UpperCAmelCase = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) _UpperCAmelCase = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
326
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(_SCREAMING_SNAKE_CASE ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
326
1
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _A : Optional[Any] = logging.get_logger('transformers.models.speecht5') def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: """simple docstring""" hf_model.apply_weight_norm() lowerCamelCase__ : int = checkpoint['''input_conv.weight_g'''] lowerCamelCase__ : str = checkpoint['''input_conv.weight_v'''] lowerCamelCase__ : Optional[int] = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): lowerCamelCase__ : List[str] = checkpoint[f"upsamples.{i}.1.weight_g"] lowerCamelCase__ : Optional[Any] = checkpoint[f"upsamples.{i}.1.weight_v"] lowerCamelCase__ : List[Any] = checkpoint[f"upsamples.{i}.1.bias"] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowerCamelCase__ : List[str] = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_g"] lowerCamelCase__ : Any = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_v"] lowerCamelCase__ : List[Any] = checkpoint[f"blocks.{i}.convs1.{j}.1.bias"] lowerCamelCase__ : int = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_g"] lowerCamelCase__ : List[Any] = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_v"] lowerCamelCase__ : int = checkpoint[f"blocks.{i}.convs2.{j}.1.bias"] lowerCamelCase__ : Union[str, Any] = checkpoint['''output_conv.1.weight_g'''] lowerCamelCase__ : Optional[Any] = checkpoint['''output_conv.1.weight_v'''] lowerCamelCase__ : Optional[Any] = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , ) -> List[Any]: """simple docstring""" if config_path is not None: lowerCamelCase__ : Tuple = SpeechTaHifiGanConfig.from_pretrained(UpperCAmelCase ) else: lowerCamelCase__ : Union[str, Any] = SpeechTaHifiGanConfig() lowerCamelCase__ : Dict = SpeechTaHifiGan(UpperCAmelCase ) lowerCamelCase__ : int = torch.load(UpperCAmelCase ) load_weights(orig_checkpoint['''model''']['''generator'''] , UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = np.load(UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = stats[0].reshape(-1 ) lowerCamelCase__ : int = stats[1].reshape(-1 ) lowerCamelCase__ : Dict = torch.from_numpy(UpperCAmelCase ).float() lowerCamelCase__ : List[str] = torch.from_numpy(UpperCAmelCase ).float() model.save_pretrained(UpperCAmelCase ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(UpperCAmelCase ) if __name__ == "__main__": _A : str = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) _A : Tuple = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
142
from __future__ import annotations from typing import Any class __SCREAMING_SNAKE_CASE : def __init__( self : Tuple , A : int = 6 ) ->None: lowerCamelCase__ : Node | None = None lowerCamelCase__ : Node | None = None self.create_linked_list(A ) def __lowerCamelCase ( self : Optional[int] , A : int ) ->None: lowerCamelCase__ : Optional[int] = Node() lowerCamelCase__ : List[str] = current_node lowerCamelCase__ : Union[str, Any] = current_node lowerCamelCase__ : List[str] = current_node for _ in range(1 , A ): lowerCamelCase__ : List[str] = Node() lowerCamelCase__ : List[Any] = current_node lowerCamelCase__ : Optional[Any] = previous_node lowerCamelCase__ : Dict = current_node lowerCamelCase__ : Union[str, Any] = self.front lowerCamelCase__ : int = previous_node def __lowerCamelCase ( self : Optional[int] ) ->bool: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def __lowerCamelCase ( self : Optional[int] ) ->Any | None: self.check_can_perform_operation() return self.front.data if self.front else None def __lowerCamelCase ( self : Optional[int] , A : Any ) ->None: if self.rear is None: return self.check_is_full() if not self.is_empty(): lowerCamelCase__ : List[str] = self.rear.next if self.rear: lowerCamelCase__ : Optional[Any] = data def __lowerCamelCase ( self : str ) ->Any: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: lowerCamelCase__ : List[Any] = self.front.data lowerCamelCase__ : Optional[Any] = None return data lowerCamelCase__ : Optional[int] = self.front lowerCamelCase__ : Optional[int] = old_front.next lowerCamelCase__ : Any = old_front.data lowerCamelCase__ : List[str] = None return data def __lowerCamelCase ( self : Dict ) ->None: if self.is_empty(): raise Exception('''Empty Queue''' ) def __lowerCamelCase ( self : int ) ->None: if self.rear and self.rear.next == self.front: raise Exception('''Full Queue''' ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ) ->None: lowerCamelCase__ : Any | None = None lowerCamelCase__ : Node | None = None lowerCamelCase__ : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
142
1
"""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 ViTImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Optional[int] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=13 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : Union[str, Any]=224 , _lowerCamelCase : List[Any]=30 , _lowerCamelCase : int=400 , _lowerCamelCase : Any=True , _lowerCamelCase : Dict=None , _lowerCamelCase : Dict=True , _lowerCamelCase : str=[0.5, 0.5, 0.5] , _lowerCamelCase : str=[0.5, 0.5, 0.5] , ): _snake_case = size if size is not None else {'''height''': 18, '''width''': 18} _snake_case = parent _snake_case = batch_size _snake_case = num_channels _snake_case = image_size _snake_case = min_resolution _snake_case = max_resolution _snake_case = do_resize _snake_case = size _snake_case = do_normalize _snake_case = image_mean _snake_case = image_std def lowercase ( self : Optional[int] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase__ ( A_ , unittest.TestCase ): __a = ViTImageProcessor if is_vision_available() else None def lowercase ( self : Optional[Any] ): _snake_case = EfficientFormerImageProcessorTester(self ) @property def lowercase ( self : Optional[int] ): return self.image_proc_tester.prepare_image_processor_dict() def lowercase ( self : str ): _snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def lowercase ( self : str ): pass def lowercase ( self : Dict ): # Initialize image_processor _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def lowercase ( self : List[str] ): # Initialize image_processor _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def lowercase ( self : List[str] ): # Initialize image_processor _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
354
"""simple docstring""" from timeit import timeit UpperCAmelCase__ = { 'MALAYALAM': True, 'String': False, 'rotor': True, 'level': True, 'A': True, 'BB': True, 'ABC': False, 'amanaplanacanalpanama': True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def _UpperCAmelCase ( __lowerCamelCase : str ) -> bool: _snake_case = 0 _snake_case = len(__lowerCamelCase ) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def _UpperCAmelCase ( __lowerCamelCase : str ) -> bool: _snake_case = len(__lowerCamelCase ) // 2 _snake_case = len(__lowerCamelCase ) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(__lowerCamelCase ) ) def _UpperCAmelCase ( __lowerCamelCase : str ) -> bool: if len(__lowerCamelCase ) <= 2: return True if s[0] == s[len(__lowerCamelCase ) - 1]: return is_palindrome_recursive(s[1:-1] ) else: return False def _UpperCAmelCase ( __lowerCamelCase : str ) -> bool: return s == s[::-1] def _UpperCAmelCase ( __lowerCamelCase : str ) -> None: _snake_case = f'''all({name}(key) is value for key, value in test_data.items())''' _snake_case = f'''from __main__ import test_data, {name}''' _snake_case = 50_00_00 _snake_case = timeit(stmt=__lowerCamelCase , setup=__lowerCamelCase , number=__lowerCamelCase ) print(f'''{name:<35} finished {number:,} runs in {result:.5f} seconds''' ) if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(F"{key:21} {value}") print('a man a plan a canal panama') # finished 500,000 runs in 0.46793 seconds benchmark_function('is_palindrome_slice') # finished 500,000 runs in 0.85234 seconds benchmark_function('is_palindrome') # finished 500,000 runs in 1.32028 seconds benchmark_function('is_palindrome_recursive') # finished 500,000 runs in 2.08679 seconds benchmark_function('is_palindrome_traversal')
40
0
'''simple docstring''' from collections.abc import Callable def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : float = a A : float = b if function(snake_case__ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case__ ) == 0: return b elif ( function(snake_case__ ) * function(snake_case__ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('''could not find root in given interval.''' ) else: A : float = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(snake_case__ ) == 0: return mid elif function(snake_case__ ) * function(snake_case__ ) < 0: A : Union[str, Any] = mid else: A : Optional[Any] = mid A : Optional[int] = start + (end - start) / 2.0 return mid def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 10_00)) import doctest doctest.testmod()
3
'''simple docstring''' class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Any = None A : Optional[Any] = None A : Tuple = graph self._normalize_graph(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Dict = len(SCREAMING_SNAKE_CASE ) A : Optional[Any] = None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if sources is int: A : Dict = [sources] if sinks is int: A : str = [sinks] if len(SCREAMING_SNAKE_CASE ) == 0 or len(SCREAMING_SNAKE_CASE ) == 0: return A : Optional[int] = sources[0] A : Union[str, Any] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE ) > 1 or len(SCREAMING_SNAKE_CASE ) > 1: A : Optional[int] = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A : Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A : Dict = max_input_flow A : Tuple = 0 A : Tuple = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A : Optional[Any] = max_input_flow A : Optional[Any] = size - 1 def __lowerCAmelCase ( self ) -> Any: """simple docstring""" if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : List[Any] = algorithm(self ) class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = flow_network A : Optional[Any] = flow_network.verticesCount A : Tuple = flow_network.sourceIndex A : Dict = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A : str = flow_network.graph A : Optional[Any] = False def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" if not self.executed: self._algorithm() A : Optional[int] = True def __lowerCAmelCase ( self ) -> Any: """simple docstring""" pass class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE ) # use this to save your result A : List[str] = -1 def __lowerCAmelCase ( self ) -> str: """simple docstring""" if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE ) A : Optional[Any] = [[0] * self.verticies_count for i in range(self.verticies_count )] A : Union[str, Any] = [0] * self.verticies_count A : List[Any] = [0] * self.verticies_count def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A : Optional[Any] = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A : Union[str, Any] = 0 while i < len(SCREAMING_SNAKE_CASE ): A : str = vertices_list[i] A : List[str] = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE ) ) A : int = 0 else: i += 1 A : Optional[Any] = sum(self.preflow[self.source_index] ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.relabel(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Dict = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Dict = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A : Dict = self.heights[to_index] if min_height is not None: A : Dict = min_height + 1 if __name__ == "__main__": lowercase : Optional[int] = [0] lowercase : List[Any] = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowercase : int = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowercase : List[str] = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowercase : List[str] = flow_network.find_maximum_flow() print(f'''maximum flow is {maximum_flow}''')
3
1
def _UpperCamelCase ( snake_case__ ) -> list: def merge(snake_case__, snake_case__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(snake_case__ ) <= 1: return collection __UpperCAmelCase : Union[str, Any] = len(snake_case__ ) // 2 return merge(merge_sort(collection[:mid] ), merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() _snake_case = input('''Enter numbers separated by a comma:\n''').strip() _snake_case = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
354
import flax.linen as nn import jax import jax.numpy as jnp class _snake_case ( nn.Module ): lowerCamelCase__: int lowerCamelCase__: jnp.dtype = jnp.floataa def _lowerCamelCase ( self: Tuple ) -> Union[str, Any]: __UpperCAmelCase : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self: Optional[Any] , __lowerCamelCase: Optional[int] ) -> List[Any]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = hidden_states.shape __UpperCAmelCase : Dict = jax.image.resize( __lowerCamelCase , shape=(batch, height * 2, width * 2, channels) , method="nearest" , ) __UpperCAmelCase : Dict = self.conv(__lowerCamelCase ) return hidden_states class _snake_case ( nn.Module ): lowerCamelCase__: int lowerCamelCase__: jnp.dtype = jnp.floataa def _lowerCamelCase ( self: str ) -> Any: __UpperCAmelCase : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self: Dict , __lowerCamelCase: str ) -> List[Any]: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) __UpperCAmelCase : Any = self.conv(__lowerCamelCase ) return hidden_states class _snake_case ( nn.Module ): lowerCamelCase__: int lowerCamelCase__: int = None lowerCamelCase__: float = 0.0 lowerCamelCase__: bool = None lowerCamelCase__: jnp.dtype = jnp.floataa def _lowerCamelCase ( self: str ) -> List[str]: __UpperCAmelCase : str = self.in_channels if self.out_channels is None else self.out_channels __UpperCAmelCase : Dict = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __UpperCAmelCase : List[str] = nn.Conv( __lowerCamelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __UpperCAmelCase : Optional[Any] = nn.Dense(__lowerCamelCase , dtype=self.dtype ) __UpperCAmelCase : Any = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __UpperCAmelCase : Optional[Any] = nn.Dropout(self.dropout_prob ) __UpperCAmelCase : Tuple = nn.Conv( __lowerCamelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __UpperCAmelCase : Optional[int] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut __UpperCAmelCase : List[Any] = None if use_nin_shortcut: __UpperCAmelCase : Dict = nn.Conv( __lowerCamelCase , kernel_size=(1, 1) , strides=(1, 1) , padding="VALID" , dtype=self.dtype , ) def __call__( self: Tuple , __lowerCamelCase: Tuple , __lowerCamelCase: str , __lowerCamelCase: Union[str, Any]=True ) -> List[Any]: __UpperCAmelCase : Dict = hidden_states __UpperCAmelCase : int = self.norma(__lowerCamelCase ) __UpperCAmelCase : Union[str, Any] = nn.swish(__lowerCamelCase ) __UpperCAmelCase : Tuple = self.conva(__lowerCamelCase ) __UpperCAmelCase : Optional[Any] = self.time_emb_proj(nn.swish(__lowerCamelCase ) ) __UpperCAmelCase : List[str] = jnp.expand_dims(jnp.expand_dims(__lowerCamelCase , 1 ) , 1 ) __UpperCAmelCase : List[str] = hidden_states + temb __UpperCAmelCase : Union[str, Any] = self.norma(__lowerCamelCase ) __UpperCAmelCase : Tuple = nn.swish(__lowerCamelCase ) __UpperCAmelCase : str = self.dropout(__lowerCamelCase , __lowerCamelCase ) __UpperCAmelCase : List[str] = self.conva(__lowerCamelCase ) if self.conv_shortcut is not None: __UpperCAmelCase : Optional[int] = self.conv_shortcut(__lowerCamelCase ) return hidden_states + residual
342
0
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCAmelCase : def __init__( self : List[Any] ): snake_case_ : List[str] = '''''' snake_case_ : Tuple = '''''' snake_case_ : int = [] snake_case_ : Optional[int] = 0 snake_case_ : Optional[Any] = 256 snake_case_ : Tuple = 0 snake_case_ : Tuple = 0 snake_case_ : Optional[Any] = 0 snake_case_ : Any = 0 def _snake_case ( self : Optional[Any] , lowercase_ : List[Any] ): snake_case_ : List[Any] = cva.imread(lowercase_ , 0 ) snake_case_ : Tuple = copy.deepcopy(self.img ) snake_case_, snake_case_, snake_case_ : List[Any] = plt.hist(self.img.ravel() , 256 , [0, 256] , label='''x''' ) snake_case_ : str = np.sum(lowercase_ ) for i in range(len(lowercase_ ) ): snake_case_ : Optional[Any] = x[i] / self.k self.sk += prk snake_case_ : Any = (self.L - 1) * self.sk if self.rem != 0: snake_case_ : Dict = int(last % last ) snake_case_ : Union[str, Any] = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(lowercase_ ) snake_case_ : int = int(np.ma.count(self.img ) / self.img[1].size ) snake_case_ : Tuple = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): snake_case_ : Union[str, Any] = self.img[j][i] if num != self.last_list[num]: snake_case_ : List[str] = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def _snake_case ( self : Tuple ): plt.hist(self.img.ravel() , 256 , [0, 256] ) def _snake_case ( self : int ): cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": lowercase__ : Any = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') lowercase__ : Any = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
264
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCAmelCase : def __init__( self : List[Any] ): snake_case_ : List[str] = '''''' snake_case_ : Tuple = '''''' snake_case_ : int = [] snake_case_ : Optional[int] = 0 snake_case_ : Optional[Any] = 256 snake_case_ : Tuple = 0 snake_case_ : Tuple = 0 snake_case_ : Optional[Any] = 0 snake_case_ : Any = 0 def _snake_case ( self : Optional[Any] , lowercase_ : List[Any] ): snake_case_ : List[Any] = cva.imread(lowercase_ , 0 ) snake_case_ : Tuple = copy.deepcopy(self.img ) snake_case_, snake_case_, snake_case_ : List[Any] = plt.hist(self.img.ravel() , 256 , [0, 256] , label='''x''' ) snake_case_ : str = np.sum(lowercase_ ) for i in range(len(lowercase_ ) ): snake_case_ : Optional[Any] = x[i] / self.k self.sk += prk snake_case_ : Any = (self.L - 1) * self.sk if self.rem != 0: snake_case_ : Dict = int(last % last ) snake_case_ : Union[str, Any] = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(lowercase_ ) snake_case_ : int = int(np.ma.count(self.img ) / self.img[1].size ) snake_case_ : Tuple = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): snake_case_ : Union[str, Any] = self.img[j][i] if num != self.last_list[num]: snake_case_ : List[str] = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def _snake_case ( self : Tuple ): plt.hist(self.img.ravel() , 256 , [0, 256] ) def _snake_case ( self : int ): cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": lowercase__ : Any = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') lowercase__ : Any = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
264
1
'''simple docstring''' from __future__ import annotations def a__ ( lowercase : float, lowercase : float, lowercase : float ) -> dict[str, float]: """simple docstring""" if (voltage, current, resistance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance < 0: raise ValueError('''Resistance cannot be negative''' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
287
'''simple docstring''' import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC lowercase__ : List[Any] = parse(importlib.metadata.version('torch')) def a__ ( lowercase : Union[str, Version], lowercase : str, lowercase : str ) -> List[str]: """simple docstring""" if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(F"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}""" ) _UpperCamelCase = STR_OPERATION_TO_FUNC[operation] if isinstance(lowercase, lowercase ): _UpperCamelCase = parse(importlib.metadata.version(lowercase ) ) return operation(lowercase, parse(lowercase ) ) def a__ ( lowercase : str, lowercase : str ) -> List[Any]: """simple docstring""" return compare_versions(lowercase, lowercase, lowercase )
287
1
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase : Union[str, Any] = NewType("""DataClass""", Any) lowerCAmelCase : List[Any] = NewType("""DataClassType""", Any) def A_ ( _UpperCAmelCase ): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." ) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = {str(_UpperCAmelCase ): choice for choice in choices} return lambda _UpperCAmelCase : str_to_choice.get(_UpperCAmelCase , _UpperCAmelCase ) def A_ ( *, _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = dataclasses.MISSING , _UpperCAmelCase = dataclasses.MISSING , _UpperCAmelCase = None , **_UpperCAmelCase , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls SCREAMING_SNAKE_CASE_: Any = {} if aliases is not None: SCREAMING_SNAKE_CASE_: Dict = aliases if help is not None: SCREAMING_SNAKE_CASE_: List[Any] = help return dataclasses.field(metadata=_UpperCAmelCase , default=_UpperCAmelCase , default_factory=_UpperCAmelCase , **_UpperCAmelCase ) class __lowercase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase : Dict = 42 def __init__( self : Dict , lowerCAmelCase__ : Optional[Any] , **lowerCAmelCase__ : List[str]): # To make the default appear when using --help if "formatter_class" not in kwargs: SCREAMING_SNAKE_CASE_: List[Any] = ArgumentDefaultsHelpFormatter super().__init__(**lowerCAmelCase__) if dataclasses.is_dataclass(lowerCAmelCase__): SCREAMING_SNAKE_CASE_: Tuple = [dataclass_types] SCREAMING_SNAKE_CASE_: List[Any] = list(lowerCAmelCase__) for dtype in self.dataclass_types: self._add_dataclass_arguments(lowerCAmelCase__) @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any]): SCREAMING_SNAKE_CASE_: Dict = F"--{field.name}" SCREAMING_SNAKE_CASE_: Dict = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , lowerCAmelCase__): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default") SCREAMING_SNAKE_CASE_: Optional[int] = kwargs.pop("aliases" , []) if isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = [aliases] SCREAMING_SNAKE_CASE_: List[Any] = getattr(field.type , "__origin__" , field.type) if origin_type is Union or (hasattr(lowerCAmelCase__ , "UnionType") and isinstance(lowerCAmelCase__ , types.UnionType)): if str not in field.type.__args__ and ( len(field.type.__args__) != 2 or type(lowerCAmelCase__) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." F" Problem encountered in field '{field.name}'.") if type(lowerCAmelCase__) not in field.type.__args__: # filter `str` in Union SCREAMING_SNAKE_CASE_: Dict = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] SCREAMING_SNAKE_CASE_: Dict = getattr(field.type , "__origin__" , field.type) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) SCREAMING_SNAKE_CASE_: int = ( field.type.__args__[0] if isinstance(lowerCAmelCase__ , field.type.__args__[1]) else field.type.__args__[1] ) SCREAMING_SNAKE_CASE_: Optional[int] = getattr(field.type , "__origin__" , field.type) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) SCREAMING_SNAKE_CASE_: Tuple = {} if origin_type is Literal or (isinstance(field.type , lowerCAmelCase__) and issubclass(field.type , lowerCAmelCase__)): if origin_type is Literal: SCREAMING_SNAKE_CASE_: Any = field.type.__args__ else: SCREAMING_SNAKE_CASE_: int = [x.value for x in field.type] SCREAMING_SNAKE_CASE_: Optional[int] = make_choice_type_function(kwargs["choices"]) if field.default is not dataclasses.MISSING: SCREAMING_SNAKE_CASE_: Any = field.default else: SCREAMING_SNAKE_CASE_: Union[str, Any] = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument SCREAMING_SNAKE_CASE_: Optional[int] = copy(lowerCAmelCase__) # Hack because type=bool in argparse does not behave as we want. SCREAMING_SNAKE_CASE_: Dict = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. SCREAMING_SNAKE_CASE_: List[Any] = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way SCREAMING_SNAKE_CASE_: List[str] = default # This tells argparse we accept 0 or 1 value after --field_name SCREAMING_SNAKE_CASE_: Optional[Any] = """?""" # This is the value that will get picked if we do --field_name (without value) SCREAMING_SNAKE_CASE_: Optional[int] = True elif isclass(lowerCAmelCase__) and issubclass(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: Dict = field.type.__args__[0] SCREAMING_SNAKE_CASE_: str = """+""" if field.default_factory is not dataclasses.MISSING: SCREAMING_SNAKE_CASE_: Any = field.default_factory() elif field.default is dataclasses.MISSING: SCREAMING_SNAKE_CASE_: Dict = True else: SCREAMING_SNAKE_CASE_: Optional[int] = field.type if field.default is not dataclasses.MISSING: SCREAMING_SNAKE_CASE_: Tuple = field.default elif field.default_factory is not dataclasses.MISSING: SCREAMING_SNAKE_CASE_: Optional[int] = field.default_factory() else: SCREAMING_SNAKE_CASE_: Optional[Any] = True parser.add_argument(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): SCREAMING_SNAKE_CASE_: int = False parser.add_argument(F"--no_{field.name}" , action="store_false" , dest=field.name , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase__ : Optional[int]): if hasattr(lowerCAmelCase__ , "_argument_group_name"): SCREAMING_SNAKE_CASE_: List[Any] = self.add_argument_group(dtype._argument_group_name) else: SCREAMING_SNAKE_CASE_: Dict = self try: SCREAMING_SNAKE_CASE_: Dict[str, type] = get_type_hints(lowerCAmelCase__) except NameError: raise RuntimeError( F"Type resolution failed for {dtype}. Try declaring the class in global scope or " "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)") except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(lowerCAmelCase__): SCREAMING_SNAKE_CASE_: Optional[int] = """.""".join(map(lowerCAmelCase__ , sys.version_info[:3])) raise RuntimeError( F"Type resolution failed for {dtype} on Python {python_version}. Try removing " "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`.") from ex raise for field in dataclasses.fields(lowerCAmelCase__): if not field.init: continue SCREAMING_SNAKE_CASE_: List[str] = type_hints[field.name] self._parse_dataclass_field(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Optional[int]=None , lowerCAmelCase__ : Dict=False , lowerCAmelCase__ : Tuple=True , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : str=None , ): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): SCREAMING_SNAKE_CASE_: str = [] if args_filename: args_files.append(Path(lowerCAmelCase__)) elif look_for_args_file and len(sys.argv): args_files.append(Path(sys.argv[0]).with_suffix(".args")) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values SCREAMING_SNAKE_CASE_: Any = ArgumentParser() args_file_parser.add_argument(lowerCAmelCase__ , type=lowerCAmelCase__ , action="append") # Use only remaining args for further parsing (remove the args_file_flag) SCREAMING_SNAKE_CASE_: Dict = args_file_parser.parse_known_args(args=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = vars(lowerCAmelCase__).get(args_file_flag.lstrip("-") , lowerCAmelCase__) if cmd_args_file_paths: args_files.extend([Path(lowerCAmelCase__) for p in cmd_args_file_paths]) SCREAMING_SNAKE_CASE_: List[Any] = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last SCREAMING_SNAKE_CASE_: str = file_args + args if args is not None else file_args + sys.argv[1:] SCREAMING_SNAKE_CASE_: Tuple = self.parse_known_args(args=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = [] for dtype in self.dataclass_types: SCREAMING_SNAKE_CASE_: List[str] = {f.name for f in dataclasses.fields(lowerCAmelCase__) if f.init} SCREAMING_SNAKE_CASE_: Optional[int] = {k: v for k, v in vars(lowerCAmelCase__).items() if k in keys} for k in keys: delattr(lowerCAmelCase__ , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = dtype(**lowerCAmelCase__) outputs.append(lowerCAmelCase__) if len(namespace.__dict__) > 0: # additional namespace. outputs.append(lowerCAmelCase__) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") return (*outputs,) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str = False): SCREAMING_SNAKE_CASE_: Tuple = set(args.keys()) SCREAMING_SNAKE_CASE_: Optional[Any] = [] for dtype in self.dataclass_types: SCREAMING_SNAKE_CASE_: int = {f.name for f in dataclasses.fields(lowerCAmelCase__) if f.init} SCREAMING_SNAKE_CASE_: List[Any] = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys()) SCREAMING_SNAKE_CASE_: List[Any] = dtype(**lowerCAmelCase__) outputs.append(lowerCAmelCase__) if not allow_extra_keys and unused_keys: raise ValueError(F"Some keys are not used by the HfArgumentParser: {sorted(lowerCAmelCase__)}") return tuple(lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int = False): with open(Path(lowerCAmelCase__) , encoding="utf-8") as open_json_file: SCREAMING_SNAKE_CASE_: Tuple = json.loads(open_json_file.read()) SCREAMING_SNAKE_CASE_: Optional[int] = self.parse_dict(lowerCAmelCase__ , allow_extra_keys=lowerCAmelCase__) return tuple(lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str = False): SCREAMING_SNAKE_CASE_: Any = self.parse_dict(yaml.safe_load(Path(lowerCAmelCase__).read_text()) , allow_extra_keys=lowerCAmelCase__) return tuple(lowerCAmelCase__)
13
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowerCamelCase : List[Any] = 1_0 def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ) -> int: for i in range(lowercase ,lowercase ): if array[i] == target: return i return -1 def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int: snake_case : Union[str, Any] = 0 snake_case : Optional[Any] = len(lowercase ) while left <= right: if right - left < precision: return lin_search(lowercase ,lowercase ,lowercase ,lowercase ) snake_case : List[str] = (left + right) // 3 + 1 snake_case : Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: snake_case : List[str] = one_third - 1 elif array[two_third] < target: snake_case : Any = two_third + 1 else: snake_case : Dict = one_third + 1 snake_case : Any = two_third - 1 else: return -1 def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ) -> int: if left < right: if right - left < precision: return lin_search(lowercase ,lowercase ,lowercase ,lowercase ) snake_case : str = (left + right) // 3 + 1 snake_case : int = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowercase ,one_third - 1 ,lowercase ,lowercase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 ,lowercase ,lowercase ,lowercase ) else: return rec_ternary_search(one_third + 1 ,two_third - 1 ,lowercase ,lowercase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase : str = input('Enter numbers separated by comma:\n').strip() lowerCamelCase : Optional[Any] = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." lowerCamelCase : int = int(input('Enter the number to be found in the list:\n').strip()) lowerCamelCase : Tuple = ite_ternary_search(collection, target) lowerCamelCase : Any = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"""Iterative search: {target} found at positions: {resulta}""") print(f"""Recursive search: {target} found at positions: {resulta}""") else: print('Not found')
124
0
'''simple docstring''' from __future__ import annotations from math import gcd def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : int = 2 , snake_case : int = 1 , snake_case : int = 3 , ) -> int | None: """simple docstring""" # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError('The input value cannot be less than 2' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(snake_case : int , snake_case : int , snake_case : int ) -> int: return (pow(snake_case , 2 ) + step) % modulus for _ in range(snake_case ): # These track the position within the cycle detection logic. a : str = seed a : List[str] = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. a : Dict = rand_fn(snake_case , snake_case , snake_case ) a : Union[str, Any] = rand_fn(snake_case , snake_case , snake_case ) a : List[str] = rand_fn(snake_case , snake_case , snake_case ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. a : int = gcd(hare - tortoise , snake_case ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. a : Dict = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse UpperCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument( """num""", type=int, help="""The value to find a divisor of""", ) parser.add_argument( """--attempts""", type=int, default=3, help="""The number of attempts before giving up""", ) UpperCamelCase : List[str] = parser.parse_args() UpperCamelCase : List[str] = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f'''{args.num} is probably prime''') else: UpperCamelCase : Optional[int] = args.num // divisor print(f'''{args.num} = {divisor} * {quotient}''')
345
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase : List[str] = {"""processing_layoutxlm""": ["""LayoutXLMProcessor"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Any = ["""LayoutXLMTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Optional[int] = ["""LayoutXLMTokenizerFast"""] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCamelCase : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
345
1
def UpperCAmelCase__ ( _A : list[int] ): '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError('''List is empty''' ) a__ =sum(_A ) / len(_A ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_A ) if __name__ == "__main__": import doctest doctest.testmod()
188
import argparse import hashlib # hashlib is only used inside the Test class import struct class __magic_name__ : '''simple docstring''' def __init__( self, lowercase_ ) -> List[str]: """simple docstring""" a__ =data a__ =[0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def _UpperCAmelCase ( lowercase_, lowercase_ ) -> Union[str, Any]: """simple docstring""" return ((n << b) | (n >> (32 - b))) & 0Xffffffff def _UpperCAmelCase ( self ) -> Optional[int]: """simple docstring""" a__ =b'''\x80''' + b'''\x00''' * (63 - (len(self.data ) + 8) % 64) a__ =self.data + padding + struct.pack('''>Q''', 8 * len(self.data ) ) return padded_data def _UpperCAmelCase ( self ) -> Any: """simple docstring""" return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def _UpperCAmelCase ( self, lowercase_ ) -> List[Any]: """simple docstring""" a__ =list(struct.unpack('''>16L''', lowercase_ ) ) + [0] * 64 for i in range(16, 80 ): a__ =self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def _UpperCAmelCase ( self ) -> Any: """simple docstring""" a__ =self.padding() a__ =self.split_blocks() for block in self.blocks: a__ =self.expand_block(lowercase_ ) a__, a__, a__, a__, a__ =self.h for i in range(0, 80 ): if 0 <= i < 20: a__ =(b & c) | ((~b) & d) a__ =0X5a827999 elif 20 <= i < 40: a__ =b ^ c ^ d a__ =0X6ed9eba1 elif 40 <= i < 60: a__ =(b & c) | (b & d) | (c & d) a__ =0X8f1bbcdc elif 60 <= i < 80: a__ =b ^ c ^ d a__ =0Xca62c1d6 a__, a__, a__, a__, a__ =( self.rotate(lowercase_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(lowercase_, 30 ), c, d, ) a__ =( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ ( ): '''simple docstring''' a__ =b'''Test String''' assert SHAaHash(_A ).final_hash() == hashlib.shaa(_A ).hexdigest() # noqa: S324 def UpperCAmelCase__ ( ): '''simple docstring''' a__ =argparse.ArgumentParser(description='''Process some strings or files''' ) parser.add_argument( '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument('''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) a__ =parser.parse_args() a__ =args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: a__ =f.read() else: a__ =bytes(_A , '''utf-8''' ) print(SHAaHash(_A ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
188
1
from __future__ import annotations def lowerCAmelCase__ ( a__ , a__ ) ->bool: '''simple docstring''' if len(a__ ) == 0: return False _UpperCamelCase = len(a__ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , a__ ) else: return binary_search(a_list[midpoint + 1 :] , a__ ) if __name__ == "__main__": lowerCamelCase__ = input('''Enter numbers separated by comma:\n''').strip() lowerCamelCase__ = [int(item.strip()) for item in user_input.split(''',''')] lowerCamelCase__ = int(input('''Enter the number to be found in the list:\n''').strip()) lowerCamelCase__ = '''''' if binary_search(sequence, target) else '''not ''' print(F"{target} was {not_str}found in {sequence}")
63
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def lowerCAmelCase__ ( a__ , a__ , a__ , a__ ) ->Optional[int]: '''simple docstring''' for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})' def lowerCAmelCase__ ( a__ , a__ , a__ , a__ , a__=True ) ->List[str]: '''simple docstring''' model.train() _UpperCamelCase = model(a__ ) _UpperCamelCase = F.mse_loss(a__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(a__ ) def lowerCAmelCase__ ( a__ , a__=False ) ->Union[str, Any]: '''simple docstring''' set_seed(42 ) _UpperCamelCase = RegressionModel() _UpperCamelCase = deepcopy(a__ ) _UpperCamelCase = RegressionDataset(length=80 ) _UpperCamelCase = DataLoader(a__ , batch_size=16 ) model.to(accelerator.device ) if sched: _UpperCamelCase = AdamW(params=model.parameters() , lr=1e-3 ) _UpperCamelCase = AdamW(params=ddp_model.parameters() , lr=1e-3 ) _UpperCamelCase = LambdaLR(a__ , lr_lambda=lambda a__ : epoch**0.65 ) _UpperCamelCase = LambdaLR(a__ , lr_lambda=lambda a__ : epoch**0.65 ) # Make a copy of `model` if sched: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = accelerator.prepare(a__ , a__ , a__ , a__ ) else: _UpperCamelCase , _UpperCamelCase = accelerator.prepare(a__ , a__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def lowerCAmelCase__ ( a__ ) ->List[Any]: '''simple docstring''' _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = get_training_setup(a__ ) # Use a single batch _UpperCamelCase , _UpperCamelCase = next(iter(a__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model _UpperCamelCase , _UpperCamelCase = accelerator.gather((ddp_input, ddp_target) ) _UpperCamelCase , _UpperCamelCase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a__ , a__ , a__ , a__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(a__ ): step_model(a__ , a__ , a__ , a__ ) else: # Sync grads step_model(a__ , a__ , a__ , a__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(a__ , a__ , a__ , a__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) _UpperCamelCase = ddp_input[torch.randperm(len(a__ ) )] def lowerCAmelCase__ ( a__ ) ->str: '''simple docstring''' _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = get_training_setup(a__ ) # Use a single batch _UpperCamelCase , _UpperCamelCase = next(iter(a__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model _UpperCamelCase , _UpperCamelCase = accelerator.gather((ddp_input, ddp_target) ) _UpperCamelCase , _UpperCamelCase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a__ , a__ , a__ , a__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(a__ ): step_model(a__ , a__ , a__ , a__ ) else: # Sync grads step_model(a__ , a__ , a__ , a__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) _UpperCamelCase = ddp_input[torch.randperm(len(a__ ) )] def lowerCAmelCase__ ( a__=False , a__=False ) ->List[Any]: '''simple docstring''' _UpperCamelCase = Accelerator( split_batches=a__ , dispatch_batches=a__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = get_training_setup(a__ ) for iteration, batch in enumerate(a__ ): _UpperCamelCase , _UpperCamelCase = batch.values() # Gather the distributed inputs and targs for the base model _UpperCamelCase , _UpperCamelCase = accelerator.gather((ddp_input, ddp_target) ) _UpperCamelCase , _UpperCamelCase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a__ , a__ , a__ , a__ , a__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(a__ ): step_model(a__ , a__ , a__ , a__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(a__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) _UpperCamelCase = ddp_input[torch.randperm(len(a__ ) )] GradientState._reset_state() def lowerCAmelCase__ ( a__=False , a__=False ) ->Dict: '''simple docstring''' _UpperCamelCase = Accelerator( split_batches=a__ , dispatch_batches=a__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = get_training_setup(a__ , a__ ) for iteration, batch in enumerate(a__ ): _UpperCamelCase , _UpperCamelCase = batch.values() # Gather the distributed inputs and targs for the base model _UpperCamelCase , _UpperCamelCase = accelerator.gather((ddp_input, ddp_target) ) _UpperCamelCase , _UpperCamelCase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(a__ , a__ , a__ , a__ , a__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(a__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(a__ ): step_model(a__ , a__ , a__ , a__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n' _UpperCamelCase = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(a__ )) if accelerator.num_processes > 1: check_model_parameters(a__ , a__ , a__ , a__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def lowerCAmelCase__ ( ) ->Union[str, Any]: '''simple docstring''' _UpperCamelCase = Accelerator() _UpperCamelCase = RegressionDataset(length=80 ) _UpperCamelCase = DataLoader(a__ , batch_size=16 ) _UpperCamelCase = RegressionDataset(length=96 ) _UpperCamelCase = DataLoader(a__ , batch_size=16 ) _UpperCamelCase , _UpperCamelCase = accelerator.prepare(a__ , a__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(a__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(a__ ) if iteration < len(a__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(a__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(a__ ) if batch_num < len(a__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def lowerCAmelCase__ ( ) ->int: '''simple docstring''' _UpperCamelCase = Accelerator() _UpperCamelCase = accelerator.state if state.local_process_index == 0: print("**Test `accumulate` gradient accumulation with dataloader break**" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("**Test NOOP `no_sync` context manager**" ) test_noop_sync(a__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("**Test Distributed `no_sync` context manager**" ) test_distributed_sync(a__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation, " , f'`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**' , ) test_gradient_accumulation(a__ , a__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("<" , "2.0" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , "`split_batches=False`, `dispatch_batches=False`**" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , f'`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**' , ) test_gradient_accumulation_with_opt_and_scheduler(a__ , a__ ) def lowerCAmelCase__ ( a__ ) ->Tuple: '''simple docstring''' main() if __name__ == "__main__": main()
63
1
'''simple docstring''' import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class _snake_case ( unittest.TestCase ): def __init__( self , _lowerCamelCase): UpperCAmelCase__ : Any = parent def snake_case__ ( self): return {} def _UpperCamelCase ( ): UpperCAmelCase__ : List[str] = """<HTML> <HEAD> <TITLE>sample document</TITLE> </HEAD> <BODY BGCOLOR=\"FFFFFF\"> <HR> <a href=\"http://google.com\">Goog</a> <H1>This is one header</H1> <H2>This is a another Header</H2> <P>Travel from <P> <B>SFO to JFK</B> <BR> <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B> <HR> <div style=\"color:#0000FF\"> <h3>Traveler <b> name </b> is <p> John Doe </p> </div>""" UpperCAmelCase__ : Tuple = """ <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> """ return [html_string_a, html_string_a] @require_bsa class _snake_case ( a__ , unittest.TestCase ): lowerCAmelCase :Optional[int] = MarkupLMFeatureExtractor if is_bsa_available() else None def snake_case__ ( self): UpperCAmelCase__ : Union[str, Any] = MarkupLMFeatureExtractionTester(self) @property def snake_case__ ( self): return self.feature_extract_tester.prepare_feat_extract_dict() def snake_case__ ( self): # Initialize feature_extractor UpperCAmelCase__ : List[Any] = self.feature_extraction_class() # Test not batched input UpperCAmelCase__ : Optional[Any] = get_html_strings()[0] UpperCAmelCase__ : Any = feature_extractor(_lowerCamelCase) # fmt: off UpperCAmelCase__ : Dict = [["""sample document""", """Goog""", """This is one header""", """This is a another Header""", """Travel from""", """SFO to JFK""", """on May 2, 2015 at 2:00 pm. For details go to confirm.com""", """Traveler""", """name""", """is""", """John Doe"""]] UpperCAmelCase__ : List[str] = [["""/html/head/title""", """/html/body/a""", """/html/body/h1""", """/html/body/h2""", """/html/body/p""", """/html/body/p/p/b[1]""", """/html/body/p/p/b[2]/i""", """/html/body/p/p/div/h3""", """/html/body/p/p/div/h3/b""", """/html/body/p/p/div/h3""", """/html/body/p/p/div/h3/p"""]] # fmt: on self.assertEqual(encoding.nodes , _lowerCamelCase) self.assertEqual(encoding.xpaths , _lowerCamelCase) # Test batched UpperCAmelCase__ : int = get_html_strings() UpperCAmelCase__ : Optional[Any] = feature_extractor(_lowerCamelCase) # fmt: off UpperCAmelCase__ : List[str] = expected_nodes + [["""My First Heading""", """My first paragraph."""]] UpperCAmelCase__ : str = expected_xpaths + [["""/html/body/h1""", """/html/body/p"""]] self.assertEqual(len(encoding.nodes) , 2) self.assertEqual(len(encoding.xpaths) , 2) self.assertEqual(encoding.nodes , _lowerCamelCase) self.assertEqual(encoding.xpaths , _lowerCamelCase)
163
'''simple docstring''' from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder __A =datasets.utils.logging.get_logger(__name__) class _snake_case ( folder_based_builder.FolderBasedBuilderConfig ): lowerCAmelCase :bool = None lowerCAmelCase :bool = None class _snake_case ( folder_based_builder.FolderBasedBuilder ): lowerCAmelCase :Optional[Any] = datasets.Audio() lowerCAmelCase :Tuple = '''audio''' lowerCAmelCase :Optional[Any] = AudioFolderConfig lowerCAmelCase :List[str] # definition at the bottom of the script lowerCAmelCase :Union[str, Any] = AudioClassification(audio_column='''audio''' , label_column='''label''' ) __A =[ '.aiff', '.au', '.avr', '.caf', '.flac', '.htk', '.svx', '.mat4', '.mat5', '.mpc2k', '.ogg', '.paf', '.pvf', '.raw', '.rf64', '.sd2', '.sds', '.ircam', '.voc', '.w64', '.wav', '.nist', '.wavex', '.wve', '.xi', '.mp3', '.opus', ] __A =AUDIO_EXTENSIONS
163
1
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCamelCase_ ( UpperCamelCase__ : Dict, UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : int, UpperCamelCase__ : List[str]=True, UpperCamelCase__ : Any="pt" ): '''simple docstring''' UpperCamelCase__ = {'''add_prefix_space''': True} if isinstance(A__, A__ ) and not line.startswith(''' ''' ) else {} UpperCamelCase__ = padding_side return tokenizer( [line], max_length=A__, padding='''max_length''' if pad_to_max_length else None, truncation=A__, return_tensors=A__, add_special_tokens=A__, **A__, ) def lowerCamelCase_ ( UpperCamelCase__ : Dict, UpperCamelCase__ : Tuple, UpperCamelCase__ : Tuple=None, ): '''simple docstring''' UpperCamelCase__ = input_ids.ne(A__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __lowercase ( lowerCamelCase__ ): '''simple docstring''' def __init__( self : Dict , _a : Dict , _a : List[Any] , _a : Dict , _a : Union[str, Any] , _a : Tuple="train" , _a : Tuple=None , _a : Optional[int]=None , _a : Tuple=None , _a : List[Any]="" , ): super().__init__() UpperCamelCase__ = Path(lowercase__ ).joinpath(type_path + '''.source''' ) UpperCamelCase__ = Path(lowercase__ ).joinpath(type_path + '''.target''' ) UpperCamelCase__ = self.get_char_lens(self.src_file ) UpperCamelCase__ = max_source_length UpperCamelCase__ = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" UpperCamelCase__ = tokenizer UpperCamelCase__ = prefix if n_obs is not None: UpperCamelCase__ = self.src_lens[:n_obs] UpperCamelCase__ = src_lang UpperCamelCase__ = tgt_lang def __len__( self : Optional[Any] ): return len(self.src_lens ) def __getitem__( self : Optional[Any] , _a : List[Any] ): UpperCamelCase__ = index + 1 # linecache starts at 1 UpperCamelCase__ = self.prefix + linecache.getline(str(self.src_file ) , lowercase__ ).rstrip('''\n''' ) UpperCamelCase__ = linecache.getline(str(self.tgt_file ) , lowercase__ ).rstrip('''\n''' ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowercase__ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right UpperCamelCase__ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer ) UpperCamelCase__ = self.tokenizer.generator if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer UpperCamelCase__ = encode_line(lowercase__ , lowercase__ , self.max_source_length , '''right''' ) UpperCamelCase__ = encode_line(lowercase__ , lowercase__ , self.max_target_length , '''right''' ) UpperCamelCase__ = source_inputs['''input_ids'''].squeeze() UpperCamelCase__ = target_inputs['''input_ids'''].squeeze() UpperCamelCase__ = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def A_ ( _a : List[str] ): return [len(lowercase__ ) for x in Path(lowercase__ ).open().readlines()] def A_ ( self : int , _a : Tuple ): UpperCamelCase__ = torch.stack([x['''input_ids'''] for x in batch] ) UpperCamelCase__ = torch.stack([x['''attention_mask'''] for x in batch] ) UpperCamelCase__ = torch.stack([x['''decoder_input_ids'''] for x in batch] ) UpperCamelCase__ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer.pad_token_id ) UpperCamelCase__ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer.pad_token_id ) UpperCamelCase__ = trim_batch(lowercase__ , lowercase__ ) UpperCamelCase__ , UpperCamelCase__ = trim_batch(lowercase__ , lowercase__ , attention_mask=lowercase__ ) UpperCamelCase__ = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowercase = getLogger(__name__) def lowerCamelCase_ ( UpperCamelCase__ : Dict ): '''simple docstring''' return list(itertools.chain.from_iterable(A__ ) ) def lowerCamelCase_ ( UpperCamelCase__ : List[str] ): '''simple docstring''' UpperCamelCase__ = get_git_info() save_json(A__, os.path.join(A__, '''git_log.json''' ) ) def lowerCamelCase_ ( UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[int], UpperCamelCase__ : Dict=4, **UpperCamelCase__ : List[Any] ): '''simple docstring''' with open(A__, '''w''' ) as f: json.dump(A__, A__, indent=A__, **A__ ) def lowerCamelCase_ ( UpperCamelCase__ : List[str] ): '''simple docstring''' with open(A__ ) as f: return json.load(A__ ) def lowerCamelCase_ ( ): '''simple docstring''' UpperCamelCase__ = git.Repo(search_parent_directories=A__ ) UpperCamelCase__ = { '''repo_id''': str(A__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : List[Any] ): '''simple docstring''' return list(map(A__, A__ ) ) def lowerCamelCase_ ( UpperCamelCase__ : str, UpperCamelCase__ : Optional[int] ): '''simple docstring''' with open(A__, '''wb''' ) as f: return pickle.dump(A__, A__ ) def lowerCamelCase_ ( UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' def remove_articles(UpperCamelCase__ : List[Any] ): return re.sub(r'''\b(a|an|the)\b''', ''' ''', A__ ) def white_space_fix(UpperCamelCase__ : List[Any] ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__ : str ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__ : str ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A__ ) ) ) ) def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : List[Any] ): '''simple docstring''' UpperCamelCase__ = normalize_answer(A__ ).split() UpperCamelCase__ = normalize_answer(A__ ).split() UpperCamelCase__ = Counter(A__ ) & Counter(A__ ) UpperCamelCase__ = sum(common.values() ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(A__ ) UpperCamelCase__ = 1.0 * num_same / len(A__ ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase_ ( UpperCamelCase__ : str, UpperCamelCase__ : List[Any] ): '''simple docstring''' return normalize_answer(A__ ) == normalize_answer(A__ ) def lowerCamelCase_ ( UpperCamelCase__ : str, UpperCamelCase__ : Optional[Any] ): '''simple docstring''' assert len(A__ ) == len(A__ ) UpperCamelCase__ = 0 for hypo, pred in zip(A__, A__ ): em += exact_match_score(A__, A__ ) if len(A__ ) > 0: em /= len(A__ ) return {"em": em} def lowerCamelCase_ ( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCamelCase_ ( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : Any ): '''simple docstring''' UpperCamelCase__ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead UpperCamelCase__ = '''dropout_rate''' for p in extra_params: if getattr(A__, A__, A__ ): if not hasattr(A__, A__ ) and not hasattr(A__, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A__ ) ) delattr(A__, A__ ) continue UpperCamelCase__ = p if hasattr(A__, A__ ) else equivalent_param[p] setattr(A__, A__, getattr(A__, A__ ) ) delattr(A__, A__ ) return hparams, config
357
from __future__ import annotations lowercase = list[list[int]] # assigning initial values to the grid lowercase = [ [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 lowercase = [ [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_ ( UpperCamelCase__ : Matrix, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int ): '''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_ ( UpperCamelCase__ : Matrix ): '''simple docstring''' for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase_ ( UpperCamelCase__ : Matrix ): '''simple docstring''' if location := find_empty_location(UpperCamelCase__ ): UpperCamelCase__ , UpperCamelCase__ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10 ): if is_safe(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): UpperCamelCase__ = digit if sudoku(UpperCamelCase__ ) is not None: return grid UpperCamelCase__ = 0 return None def lowerCamelCase_ ( UpperCamelCase__ : Matrix ): '''simple docstring''' for row in grid: for cell in row: print(UpperCamelCase__, 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:""") lowercase = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
35
0
"""simple docstring""" import os lowerCAmelCase : Optional[int] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} def a__ ( snake_case__ ) -> int: lowerCamelCase = 0 lowerCamelCase = 0 while index < len(__snake_case ) - 1: lowerCamelCase = SYMBOLS[numerals[index]] lowerCamelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def a__ ( snake_case__ ) -> str: lowerCamelCase = """""" lowerCamelCase = num // 10_00 numerals += m_count * "M" num %= 10_00 lowerCamelCase = num // 1_00 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_00 lowerCamelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def a__ ( snake_case__ = "/p089_roman.txt" ) -> int: lowerCamelCase = 0 with open(os.path.dirname(__snake_case ) + roman_numerals_filename ) as filea: lowerCamelCase = filea.readlines() for line in lines: lowerCamelCase = line.strip() lowerCamelCase = parse_roman_numerals(__snake_case ) lowerCamelCase = generate_roman_numerals(__snake_case ) savings += len(__snake_case ) - len(__snake_case ) return savings if __name__ == "__main__": print(F"""{solution() = }""")
291
'''simple docstring''' from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline a_ : Any = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class __UpperCamelCase ( lowerCamelCase__ ): def __init__( self, **lowerCAmelCase ): """simple docstring""" super().__init__(**lowerCAmelCase ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self, lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" return super().__call__(lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, **lowerCAmelCase ): """simple docstring""" lowerCamelCase_ ={} if "candidate_labels" in kwargs: lowerCamelCase_ =kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: lowerCamelCase_ =kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase="This is a sound of {}." ): """simple docstring""" if isinstance(lowerCAmelCase, lowerCAmelCase ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png lowerCamelCase_ =requests.get(lowerCAmelCase ).content else: with open(lowerCAmelCase, '''rb''' ) as f: lowerCamelCase_ =f.read() if isinstance(lowerCAmelCase, lowerCAmelCase ): lowerCamelCase_ =ffmpeg_read(lowerCAmelCase, self.feature_extractor.sampling_rate ) if not isinstance(lowerCAmelCase, np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) lowerCamelCase_ =self.feature_extractor( [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors='''pt''' ) lowerCamelCase_ =candidate_labels lowerCamelCase_ =[hypothesis_template.format(lowerCAmelCase ) for x in candidate_labels] lowerCamelCase_ =self.tokenizer(lowerCAmelCase, return_tensors=self.framework, padding=lowerCAmelCase ) lowerCamelCase_ =[text_inputs] return inputs def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =model_inputs.pop('''candidate_labels''' ) lowerCamelCase_ =model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0], lowerCAmelCase ): lowerCamelCase_ =text_inputs[0] else: # Batching case. lowerCamelCase_ =text_inputs[0][0] lowerCamelCase_ =self.model(**lowerCAmelCase, **lowerCAmelCase ) lowerCamelCase_ ={ '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =model_outputs.pop('''candidate_labels''' ) lowerCamelCase_ =model_outputs['''logits'''][0] if self.framework == "pt": lowerCamelCase_ =logits.softmax(dim=0 ) lowerCamelCase_ =probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) lowerCamelCase_ =[ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(lowerCAmelCase, lowerCAmelCase ), key=lambda lowerCAmelCase : -x[0] ) ] return result
75
0
"""simple docstring""" def UpperCAmelCase_ (_lowerCAmelCase : list ): __UpperCamelCase : List[Any] = False while is_sorted is False: # Until all the indices are traversed keep looping __UpperCamelCase : List[Any] = True for i in range(0 , len(_lowerCAmelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __UpperCamelCase : Optional[Any] = input_list[i + 1], input_list[i] # swapping if elements not in order __UpperCamelCase : Any = False for i in range(1 , len(_lowerCAmelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __UpperCamelCase : Union[str, Any] = input_list[i + 1], input_list[i] # swapping if elements not in order __UpperCamelCase : Any = False return input_list if __name__ == "__main__": print("Enter list to be sorted") lowercase : Any = [int(x) for x in input().split()] # inputing elements of the list in one line lowercase : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
357
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
171
0
'''simple docstring''' a : Optional[Any] = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '&': '.-...', '@': '.--.-.', ':': '---...', ',': '--..--', '.': '.-.-.-', '\'': '.----.', '"': '.-..-.', '?': '..--..', '/': '-..-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '!': '-.-.--', ' ': '/' } # Exclamation mark is not in ITU-R recommendation # fmt: on a : Optional[Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def __magic_name__ ( ) -> None: '''simple docstring''' snake_case_ = '''Morse code here!''' print(__UpperCAmelCase ) snake_case_ = encrypt(__UpperCAmelCase ) print(__UpperCAmelCase ) snake_case_ = decrypt(__UpperCAmelCase ) print(__UpperCAmelCase ) if __name__ == "__main__": main()
56
'''simple docstring''' from ..utils import DummyObject, requires_backends class a ( metaclass=_lowerCamelCase ): snake_case_ = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *lowercase_ : Optional[int] , **lowercase_ : int ): requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def A_ ( cls : List[Any] , *lowercase_ : Optional[Any] , **lowercase_ : str ): requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def A_ ( cls : Tuple , *lowercase_ : Union[str, Any] , **lowercase_ : List[Any] ): requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
56
1
'''simple docstring''' import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType _lowerCamelCase : Any = logging.get_logger(__name__) class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = '''vision-encoder-decoder''' __lowerCAmelCase = True def __init__(self : int , **_lowerCAmelCase : Optional[Any] ): super().__init__(**_lowerCAmelCase ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( F"""A configuraton of type {self.model_type} cannot be instantiated because """ F"""not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}""" ) A = kwargs.pop("""encoder""" ) A = encoder_config.pop("""model_type""" ) A = kwargs.pop("""decoder""" ) A = decoder_config.pop("""model_type""" ) A = AutoConfig.for_model(_lowerCAmelCase , **_lowerCAmelCase ) A = AutoConfig.for_model(_lowerCAmelCase , **_lowerCAmelCase ) A = True @classmethod def A (cls : List[Any] , _lowerCAmelCase : PretrainedConfig , _lowerCAmelCase : PretrainedConfig , **_lowerCAmelCase : List[Any] ): logger.info("""Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) A = True A = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_lowerCAmelCase ) def A (self : Tuple ): A = copy.deepcopy(self.__dict__ ) A = self.encoder.to_dict() A = self.decoder.to_dict() A = self.__class__.model_type return output class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = version.parse('''1.11''' ) @property def A (self : Optional[Any] ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def A (self : int ): return 1e-4 @property def A (self : Union[str, Any] ): return OrderedDict({"""last_hidden_state""": {0: """batch""", 1: """encoder_sequence"""}} ) class __UpperCAmelCase ( A__ ): '''simple docstring''' @property def A (self : Tuple ): A = OrderedDict() A = {0: """batch""", 1: """past_decoder_sequence + sequence"""} A = {0: """batch""", 1: """past_decoder_sequence + sequence"""} A = {0: """batch""", 1: """encoder_sequence"""} return common_inputs def A (self : Optional[Any] , _lowerCAmelCase : "PreTrainedTokenizerBase" , _lowerCAmelCase : int = -1 , _lowerCAmelCase : int = -1 , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional["TensorType"] = None , ): import torch A = OrderedDict() A = super().generate_dummy_inputs( _lowerCAmelCase , batch_size=_lowerCAmelCase , seq_length=_lowerCAmelCase , is_pair=_lowerCAmelCase , framework=_lowerCAmelCase ) A , A = dummy_input["""input_ids"""].shape A = (batch, encoder_sequence, self._config.encoder_hidden_size) A = dummy_input.pop("""input_ids""" ) A = dummy_input.pop("""attention_mask""" ) A = torch.zeros(_lowerCAmelCase ) return common_inputs class __UpperCAmelCase ( A__ ): '''simple docstring''' @property def A (self : List[Any] ): pass def A (self : Union[str, Any] , _lowerCAmelCase : PretrainedConfig ): return VisionEncoderDecoderEncoderOnnxConfig(_lowerCAmelCase ) def A (self : int , _lowerCAmelCase : PretrainedConfig , _lowerCAmelCase : PretrainedConfig , _lowerCAmelCase : str = "default" ): A = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(_lowerCAmelCase , _lowerCAmelCase )
337
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Optional[Any] = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ 'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Swinv2ForImageClassification', 'Swinv2ForMaskedImageModeling', 'Swinv2Model', 'Swinv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys _lowerCamelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
337
1
_a = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609_344, "knot": 1.852, } _a = { "km/h": 1.0, "m/s": 0.277_777_778, "mph": 0.621_371_192, "knot": 0.539_956_803, } def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ) -> Dict: '''simple docstring''' if unit_to not in speed_chart or unit_from not in speed_chart_inverse: lowerCamelCase__ = ( F'Incorrect \'from_type\' or \'to_type\' value: {unit_from!r}, {unit_to!r}\n' F'Valid values are: {", ".join(snake_case_ )}' ) raise ValueError(snake_case_ ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to] ,3 ) if __name__ == "__main__": import doctest doctest.testmod()
209
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowercase_ : Optional[int] = logging.get_logger(__name__) lowercase_ : Dict = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class __lowerCAmelCase ( UpperCAmelCase__ ): snake_case_ : Tuple = "codegen" snake_case_ : Optional[Any] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Tuple , snake_case__ : Any=50_400 , snake_case__ : int=2_048 , snake_case__ : Optional[Any]=2_048 , snake_case__ : Tuple=4_096 , snake_case__ : List[str]=28 , snake_case__ : List[Any]=16 , snake_case__ : int=64 , snake_case__ : Tuple=None , snake_case__ : Union[str, Any]="gelu_new" , snake_case__ : List[Any]=0.0 , snake_case__ : List[str]=0.0 , snake_case__ : Optional[int]=0.0 , snake_case__ : Dict=1e-5 , snake_case__ : int=0.02 , snake_case__ : Union[str, Any]=True , snake_case__ : str=50_256 , snake_case__ : List[str]=50_256 , snake_case__ : Optional[int]=False , **snake_case__ : str , ): """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_ctx _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = n_inner _UpperCAmelCase = rotary_dim _UpperCAmelCase = activation_function _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache _UpperCAmelCase = bos_token_id _UpperCAmelCase = eos_token_id super().__init__( bos_token_id=snake_case__ , eos_token_id=snake_case__ , tie_word_embeddings=snake_case__ , **snake_case__ ) class __lowerCAmelCase ( UpperCAmelCase__ ): def __init__( self : List[str] , snake_case__ : PretrainedConfig , snake_case__ : str = "default" , snake_case__ : List[PatchingSpec] = None , snake_case__ : bool = False , ): """simple docstring""" super().__init__(snake_case__ , task=snake_case__ , patching_specs=snake_case__ , use_past=snake_case__ ) if not getattr(self._config , "pad_token_id" , snake_case__ ): # TODO: how to do that better? _UpperCAmelCase = 0 @property def UpperCamelCase ( self : Tuple ): """simple docstring""" _UpperCAmelCase = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(snake_case__ , direction="inputs" ) _UpperCAmelCase = {0: "batch", 1: "past_sequence + sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return common_inputs @property def UpperCamelCase ( self : int ): """simple docstring""" return self._config.n_layer @property def UpperCamelCase ( self : List[str] ): """simple docstring""" return self._config.n_head def UpperCamelCase ( self : List[Any] , snake_case__ : PreTrainedTokenizer , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional[TensorType] = None , ): """simple docstring""" _UpperCAmelCase = super(snake_case__ , self ).generate_dummy_inputs( snake_case__ , batch_size=snake_case__ , seq_length=snake_case__ , is_pair=snake_case__ , framework=snake_case__ ) # We need to order the input in the way they appears in the forward() _UpperCAmelCase = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch _UpperCAmelCase , _UpperCAmelCase = common_inputs["input_ids"].shape # Not using the same length for past_key_values _UpperCAmelCase = seqlen + 2 _UpperCAmelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _UpperCAmelCase = [ (torch.zeros(snake_case__ ), torch.zeros(snake_case__ )) for _ in range(self.num_layers ) ] _UpperCAmelCase = common_inputs["attention_mask"] if self.use_past: _UpperCAmelCase = ordered_inputs["attention_mask"].dtype _UpperCAmelCase = torch.cat( [ordered_inputs["attention_mask"], torch.ones(snake_case__ , snake_case__ , dtype=snake_case__ )] , dim=1 ) return ordered_inputs @property def UpperCamelCase ( self : Any ): """simple docstring""" return 13
133
0
import requests lowercase : Dict = "" # <-- Put your OpenWeatherMap appid here! lowercase : str = "https://api.openweathermap.org/data/2.5/" def UpperCAmelCase_ (_lowerCAmelCase : str = "Chicago" , _lowerCAmelCase : str = APPID ): return requests.get(URL_BASE + "weather" , params=locals() ).json() def UpperCAmelCase_ (_lowerCAmelCase : str = "Kolkata, India" , _lowerCAmelCase : str = APPID ): return requests.get(URL_BASE + "forecast" , params=locals() ).json() def UpperCAmelCase_ (_lowerCAmelCase : float = 55.68 , _lowerCAmelCase : float = 12.57 , _lowerCAmelCase : str = APPID ): return requests.get(URL_BASE + "onecall" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: lowercase : Tuple = input("Enter a location:").strip() if location: pprint(current_weather(location)) else: break
353
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase__ ) class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" lowercase : str = field(default='text-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) lowercase : ClassVar[Features] = Features({'text': Value('string' )} ) lowercase : ClassVar[Features] = Features({'labels': ClassLabel} ) lowercase : str = "text" lowercase : str = "labels" def __lowerCamelCase ( self , __UpperCamelCase ) -> List[str]: '''simple docstring''' if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __UpperCamelCase ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __UpperCamelCase : int = copy.deepcopy(self ) __UpperCamelCase : List[Any] = self.label_schema.copy() __UpperCamelCase : Union[str, Any] = features[self.label_column] __UpperCamelCase : Optional[Any] = label_schema return task_template @property def __lowerCamelCase ( self ) -> Dict[str, str]: '''simple docstring''' return { self.text_column: "text", self.label_column: "labels", }
171
0
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase__( __lowerCamelCase , unittest.TestCase): UpperCAmelCase__ : int = LxmertTokenizer UpperCAmelCase__ : Tuple = LxmertTokenizerFast UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : int = True def lowerCAmelCase__ ( self: str ): super().setUp() __lowerCamelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __lowerCamelCase = 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] ) ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Optional[int] ): __lowerCamelCase = """UNwant\u00E9d,running""" __lowerCamelCase = """unwanted, running""" return input_text, output_text def lowerCAmelCase__ ( self: Tuple ): __lowerCamelCase = self.tokenizer_class(self.vocab_file ) __lowerCamelCase = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(UpperCamelCase_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , [7, 4, 5, 10, 8, 9] ) def lowerCAmelCase__ ( self: str ): if not self.test_rust_tokenizer: return __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = """I was born in 92000, and this is falsé.""" __lowerCamelCase = tokenizer.tokenize(UpperCamelCase_ ) __lowerCamelCase = rust_tokenizer.tokenize(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ) __lowerCamelCase = rust_tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = tokenizer.encode(UpperCamelCase_ ) __lowerCamelCase = rust_tokenizer.encode(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
12
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _lowerCAmelCase :str = object() # For specifying empty leaf dict `{}` _lowerCAmelCase :str = object() def lowerCamelCase_ (UpperCamelCase__ : List[str] , UpperCamelCase__ : int ): _UpperCAmelCase : Dict = tuple((re.compile(x + '''$''' ) for x in qs) ) for i in range(len(UpperCamelCase__ ) - len(UpperCamelCase__ ) + 1 ): _UpperCAmelCase : str = [x.match(UpperCamelCase__ ) for x, y in zip(UpperCamelCase__ , ks[i:] )] if matches and all(UpperCamelCase__ ): return True return False def lowerCamelCase_ (UpperCamelCase__ : List[str] ): def replace(UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple ): for rule, replacement in rules: if _match(UpperCamelCase__ , UpperCamelCase__ ): return replacement return val return replace def lowerCamelCase_ (): return [ # embeddings (("transformer", "wpe", "embedding"), P('''mp''' , UpperCamelCase__ )), (("transformer", "wte", "embedding"), P('''mp''' , UpperCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCamelCase__ , '''mp''' )), (("attention", "out_proj", "kernel"), P('''mp''' , UpperCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCamelCase__ , '''mp''' )), (("mlp", "c_fc", "bias"), P('''mp''' )), (("mlp", "c_proj", "kernel"), P('''mp''' , UpperCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def lowerCamelCase_ (UpperCamelCase__ : str ): _UpperCAmelCase : List[str] = _get_partition_rules() _UpperCAmelCase : List[str] = _replacement_rules(UpperCamelCase__ ) _UpperCAmelCase : List[Any] = {k: _unmatched for k in flatten_dict(UpperCamelCase__ )} _UpperCAmelCase : int = {k: replace(UpperCamelCase__ , UpperCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCamelCase__ ) )
263
0
import torch from diffusers import DiffusionPipeline class A_ ( _lowerCamelCase ): def __init__(self :Optional[Any] , _UpperCamelCase :Dict , _UpperCamelCase :List[Any] )-> List[Any]: super().__init__() self.register_modules(unet=_UpperCamelCase , scheduler=_UpperCamelCase ) def __call__(self :str )-> Dict: __A = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __A = 1 __A = self.unet(_UpperCamelCase , _UpperCamelCase ).sample __A = self.scheduler.step(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ).prev_sample __A = scheduler_output - scheduler_output + torch.ones_like(_UpperCamelCase ) return result
250
import math def _a ( lowerCamelCase: int ) -> int: '''simple docstring''' if not isinstance(lowerCamelCase , lowerCamelCase ): __A = F"""Input value of [number={number}] must be an integer""" raise TypeError(lowerCamelCase ) if number < 1: __A = F"""Input value of [number={number}] must be > 0""" raise ValueError(lowerCamelCase ) elif number == 1: return 3 elif number == 2: return 5 else: __A = int(math.log(number // 3 , 2 ) ) + 2 __A = [3, 5] __A = 2 __A = 3 for block in range(1 , lowerCamelCase ): for _ in range(lowerCamelCase ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): snake_case__ : Optional[Any] = 0 try: snake_case__ : int = proth(number) except ValueError: print(f'ValueError: there is no {number}th Proth number') continue print(f'The {number}th Proth number: {value}')
250
1
from collections.abc import Sequence def _lowercase ( lowercase__ , lowercase__ ): return sum(c * (x**i) for i, c in enumerate(lowercase__ ) ) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : Optional[int] = 0.0 for coeff in reversed(lowercase__ ): __lowerCAmelCase : str = result * x + coeff return result if __name__ == "__main__": _UpperCamelCase = (0.0, 0.0, 5.0, 9.3, 7.0) _UpperCamelCase = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
275
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = XCLIPTextConfig() # derive patch size from model name _lowerCAmelCase = model_name.find("""patch""" ) _lowerCAmelCase = int(model_name[start_idx + len("""patch""" ) : start_idx + len("""patch""" ) + 2] ) _lowerCAmelCase = XCLIPVisionConfig(patch_size=snake_case , num_frames=snake_case ) if "large" in model_name: _lowerCAmelCase = 7_68 _lowerCAmelCase = 30_72 _lowerCAmelCase = 12 _lowerCAmelCase = 10_24 _lowerCAmelCase = 40_96 _lowerCAmelCase = 16 _lowerCAmelCase = 24 _lowerCAmelCase = 7_68 _lowerCAmelCase = 30_72 if model_name == "xclip-large-patch14-16-frames": _lowerCAmelCase = 3_36 _lowerCAmelCase = XCLIPConfig.from_text_vision_configs(snake_case , snake_case ) if "large" in model_name: _lowerCAmelCase = 7_68 return config def _UpperCAmelCase ( snake_case ): """simple docstring""" if name == "token_embedding.weight": _lowerCAmelCase = name.replace("""token_embedding.weight""" , """text_model.embeddings.token_embedding.weight""" ) if name == "positional_embedding": _lowerCAmelCase = name.replace("""positional_embedding""" , """text_model.embeddings.position_embedding.weight""" ) if "ln_1" in name: _lowerCAmelCase = name.replace("""ln_1""" , """layer_norm1""" ) if "ln_2" in name: _lowerCAmelCase = name.replace("""ln_2""" , """layer_norm2""" ) if "c_fc" in name: _lowerCAmelCase = name.replace("""c_fc""" , """fc1""" ) if "c_proj" in name: _lowerCAmelCase = name.replace("""c_proj""" , """fc2""" ) if name.startswith("""transformer.resblocks""" ): _lowerCAmelCase = name.replace("""transformer.resblocks""" , """text_model.encoder.layers""" ) if "attn.out_proj" in name and "message" not in name: _lowerCAmelCase = name.replace("""attn.out_proj""" , """self_attn.out_proj""" ) if "ln_final" in name: _lowerCAmelCase = name.replace("""ln_final""" , """text_model.final_layer_norm""" ) # visual encoder if name == "visual.class_embedding": _lowerCAmelCase = name.replace("""visual.class_embedding""" , """vision_model.embeddings.class_embedding""" ) if name == "visual.positional_embedding": _lowerCAmelCase = name.replace("""visual.positional_embedding""" , """vision_model.embeddings.position_embedding.weight""" ) if name.startswith("""visual.transformer.resblocks""" ): _lowerCAmelCase = name.replace("""visual.transformer.resblocks""" , """vision_model.encoder.layers""" ) if "visual.conv1" in name: _lowerCAmelCase = name.replace("""visual.conv1""" , """vision_model.embeddings.patch_embedding""" ) if "visual.ln_pre" in name: _lowerCAmelCase = name.replace("""visual.ln_pre""" , """vision_model.pre_layernorm""" ) if "visual.ln_post" in name: _lowerCAmelCase = name.replace("""visual.ln_post""" , """vision_model.post_layernorm""" ) if "visual.proj" in name: _lowerCAmelCase = name.replace("""visual.proj""" , """visual_projection.weight""" ) if "text_projection" in name: _lowerCAmelCase = name.replace("""text_projection""" , """text_projection.weight""" ) # things on top if "prompts_visual_proj" in name: _lowerCAmelCase = name.replace("""prompts_visual_proj""" , """prompts_visual_projection""" ) if "prompts_visual_ln" in name: _lowerCAmelCase = name.replace("""prompts_visual_ln""" , """prompts_visual_layernorm""" ) # mit if name == "mit.positional_embedding": _lowerCAmelCase = name.replace("""positional""" , """position""" ) if name.startswith("""mit.resblocks""" ): _lowerCAmelCase = name.replace("""mit.resblocks""" , """mit.encoder.layers""" ) # prompts generator if name.startswith("""prompts_generator.norm""" ): _lowerCAmelCase = name.replace("""prompts_generator.norm""" , """prompts_generator.layernorm""" ) return name def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" for key in orig_state_dict.copy().keys(): _lowerCAmelCase = orig_state_dict.pop(snake_case ) if "attn.in_proj" in key: _lowerCAmelCase = key.split(""".""" ) if key.startswith("""visual""" ): _lowerCAmelCase = key_split[3] _lowerCAmelCase = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: _lowerCAmelCase = val[ :dim, : ] _lowerCAmelCase = val[ dim : dim * 2, : ] _lowerCAmelCase = val[ -dim:, : ] else: _lowerCAmelCase = val[ :dim ] _lowerCAmelCase = val[ dim : dim * 2 ] _lowerCAmelCase = val[ -dim: ] else: if "weight" in key: _lowerCAmelCase = val[ :dim, : ] _lowerCAmelCase = val[ dim : dim * 2, : ] _lowerCAmelCase = val[ -dim:, : ] else: _lowerCAmelCase = val[:dim] _lowerCAmelCase = val[ dim : dim * 2 ] _lowerCAmelCase = val[-dim:] elif key.startswith("""mit""" ): _lowerCAmelCase = key_split[2] _lowerCAmelCase = config.vision_config.mit_hidden_size if "weight" in key: _lowerCAmelCase = val[:dim, :] _lowerCAmelCase = val[dim : dim * 2, :] _lowerCAmelCase = val[-dim:, :] else: _lowerCAmelCase = val[:dim] _lowerCAmelCase = val[dim : dim * 2] _lowerCAmelCase = val[-dim:] else: _lowerCAmelCase = key_split[2] _lowerCAmelCase = config.text_config.hidden_size if "weight" in key: _lowerCAmelCase = val[:dim, :] _lowerCAmelCase = val[ dim : dim * 2, : ] _lowerCAmelCase = val[-dim:, :] else: _lowerCAmelCase = val[:dim] _lowerCAmelCase = val[ dim : dim * 2 ] _lowerCAmelCase = val[-dim:] else: _lowerCAmelCase = rename_key(snake_case ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: _lowerCAmelCase = val.T _lowerCAmelCase = val return orig_state_dict def _UpperCAmelCase ( snake_case ): """simple docstring""" if num_frames == 8: _lowerCAmelCase = """eating_spaghetti_8_frames.npy""" elif num_frames == 16: _lowerCAmelCase = """eating_spaghetti.npy""" elif num_frames == 32: _lowerCAmelCase = """eating_spaghetti_32_frames.npy""" _lowerCAmelCase = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename=snake_case , repo_type="""dataset""" , ) _lowerCAmelCase = np.load(snake_case ) return list(snake_case ) def _UpperCAmelCase ( snake_case , snake_case=None , snake_case=False ): """simple docstring""" _lowerCAmelCase = { # fully supervised kinetics-400 checkpoints """xclip-base-patch32""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth""", """xclip-base-patch32-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth""" ), """xclip-base-patch16""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth""", """xclip-base-patch16-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth""" ), """xclip-large-patch14""": """https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb""", """xclip-large-patch14-16-frames""": """https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f""", # fully supervised kinetics-600 checkpoints """xclip-base-patch16-kinetics-600""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth""" ), """xclip-base-patch16-kinetics-600-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth""" ), """xclip-large-patch14-kinetics-600""": """https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be""", # few shot """xclip-base-patch16-hmdb-2-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth""" ), """xclip-base-patch16-hmdb-4-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth""" ), """xclip-base-patch16-hmdb-8-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth""" ), """xclip-base-patch16-hmdb-16-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth""" ), """xclip-base-patch16-ucf-2-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth""" ), """xclip-base-patch16-ucf-4-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth""" ), """xclip-base-patch16-ucf-8-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth""" ), """xclip-base-patch16-ucf-16-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth""" ), # zero shot """xclip-base-patch16-zero-shot""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth""", } _lowerCAmelCase = model_to_url[model_name] _lowerCAmelCase = 8 if "16-frames" in model_name: _lowerCAmelCase = 16 elif "shot" in model_name: _lowerCAmelCase = 32 _lowerCAmelCase = get_xclip_config(snake_case , snake_case ) _lowerCAmelCase = XCLIPModel(snake_case ) model.eval() if "drive" in checkpoint_url: _lowerCAmelCase = """pytorch_model.bin""" gdown.cached_download(snake_case , snake_case , quiet=snake_case ) _lowerCAmelCase = torch.load(snake_case , map_location="""cpu""" )["""model"""] else: _lowerCAmelCase = torch.hub.load_state_dict_from_url(snake_case )["""model"""] _lowerCAmelCase = convert_state_dict(snake_case , snake_case ) _lowerCAmelCase = XCLIPModel(snake_case ) _lowerCAmelCase , _lowerCAmelCase = model.load_state_dict(snake_case , strict=snake_case ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() _lowerCAmelCase = 3_36 if model_name == """xclip-large-patch14-16-frames""" else 2_24 _lowerCAmelCase = VideoMAEImageProcessor(size=snake_case ) _lowerCAmelCase = CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32""" ) _lowerCAmelCase = CLIPTokenizerFast.from_pretrained("""openai/clip-vit-base-patch32""" ) _lowerCAmelCase = XCLIPProcessor(image_processor=snake_case , tokenizer=snake_case ) _lowerCAmelCase = prepare_video(snake_case ) _lowerCAmelCase = processor( text=["""playing sports""", """eating spaghetti""", """go shopping"""] , videos=snake_case , return_tensors="""pt""" , padding=snake_case ) print("""Shape of pixel values:""" , inputs.pixel_values.shape ) with torch.no_grad(): _lowerCAmelCase = model(**snake_case ) # Verify outputs _lowerCAmelCase = outputs.logits_per_video _lowerCAmelCase = logits_per_video.softmax(dim=1 ) print("""Probs:""" , snake_case ) # kinetics-400 if model_name == "xclip-base-patch32": _lowerCAmelCase = torch.tensor([[0.0_019, 0.9_951, 0.0_030]] ) elif model_name == "xclip-base-patch32-16-frames": _lowerCAmelCase = torch.tensor([[7.09_99E-04, 9.98_83E-01, 4.55_80E-04]] ) elif model_name == "xclip-base-patch16": _lowerCAmelCase = torch.tensor([[0.0_083, 0.9_681, 0.0_236]] ) elif model_name == "xclip-base-patch16-16-frames": _lowerCAmelCase = torch.tensor([[7.69_37E-04, 9.97_28E-01, 1.94_73E-03]] ) elif model_name == "xclip-large-patch14": _lowerCAmelCase = torch.tensor([[0.0_062, 0.9_864, 0.0_075]] ) elif model_name == "xclip-large-patch14-16-frames": _lowerCAmelCase = torch.tensor([[3.38_77E-04, 9.99_37E-01, 2.88_88E-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": _lowerCAmelCase = torch.tensor([[0.0_555, 0.8_914, 0.0_531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": _lowerCAmelCase = torch.tensor([[3.85_54E-04, 9.99_29E-01, 3.27_54E-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": _lowerCAmelCase = torch.tensor([[0.0_036, 0.9_920, 0.0_045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": _lowerCAmelCase = torch.tensor([[7.18_90E-06, 9.99_94E-01, 5.65_59E-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": _lowerCAmelCase = torch.tensor([[1.03_20E-05, 9.99_93E-01, 6.24_35E-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": _lowerCAmelCase = torch.tensor([[4.13_77E-06, 9.99_90E-01, 9.83_86E-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": _lowerCAmelCase = torch.tensor([[4.13_47E-05, 9.99_62E-01, 3.34_11E-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": _lowerCAmelCase = torch.tensor([[8.58_57E-05, 9.99_28E-01, 6.32_91E-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": _lowerCAmelCase = torch.tensor([[8.58_57E-05, 9.99_28E-01, 6.32_91E-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": _lowerCAmelCase = torch.tensor([[0.0_027, 0.9_904, 0.0_070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": _lowerCAmelCase = torch.tensor([[9.82_19E-04, 9.95_93E-01, 3.08_63E-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": _lowerCAmelCase = torch.tensor([[3.50_82E-04, 9.97_85E-01, 1.79_66E-03]] ) else: raise ValueError(F'Model name {model_name} not supported' ) assert torch.allclose(snake_case , snake_case , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case ) if push_to_hub: print("""Pushing model, processor and slow tokenizer files to the hub...""" ) model.push_to_hub(snake_case , organization="""nielsr""" ) processor.push_to_hub(snake_case , organization="""nielsr""" ) slow_tokenizer.push_to_hub(snake_case , organization="""nielsr""" ) if __name__ == "__main__": A__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""xclip-base-patch32""", type=str, help="""Name of the model.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) A__ = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
82
0
import torch from diffusers import StableDiffusionPipeline lowerCamelCase : Dict = "path-to-your-trained-model" lowerCamelCase : Tuple = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('''cuda''') lowerCamelCase : Union[str, Any] = "A photo of sks dog in a bucket" lowerCamelCase : List[Any] = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0] image.save('''dog-bucket.png''')
368
def snake_case_ ( lowerCAmelCase_ : int ): __lowercase : int = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def snake_case_ ( lowerCAmelCase_ : int = 5000 ): __lowercase : Optional[int] = [(i * (3 * i - 1)) // 2 for i in range(1 , lowerCAmelCase_ )] for i, pentagonal_i in enumerate(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): __lowercase : int = pentagonal_nums[j] __lowercase : Optional[int] = pentagonal_i + pentagonal_j __lowercase : Union[str, Any] = pentagonal_j - pentagonal_i if is_pentagonal(lowerCAmelCase_ ) and is_pentagonal(lowerCAmelCase_ ): return b return -1 if __name__ == "__main__": print(f'''{solution() = }''')
306
0
"""simple docstring""" def lowercase_ ( _snake_case = 50 ): SCREAMING_SNAKE_CASE__ : Tuple = [1] * (length + 1) for row_length in range(3 ,length + 1 ): for block_length in range(3 ,row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
25
"""simple docstring""" import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _UpperCAmelCase ( __lowerCamelCase : int = 3 ) -> qiskit.result.counts.Counts: if isinstance(__lowerCamelCase , __lowerCamelCase ): raise TypeError('''number of qubits must be a integer.''' ) if number_of_qubits <= 0: raise ValueError('''number of qubits must be > 0.''' ) if math.floor(__lowerCamelCase ) != number_of_qubits: raise ValueError('''number of qubits must be exact integer.''' ) if number_of_qubits > 10: raise ValueError('''number of qubits too large to simulate(>10).''' ) _snake_case = QuantumRegister(__lowerCamelCase , '''qr''' ) _snake_case = ClassicalRegister(__lowerCamelCase , '''cr''' ) _snake_case = QuantumCircuit(__lowerCamelCase , __lowerCamelCase ) _snake_case = number_of_qubits for i in range(__lowerCamelCase ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__lowerCamelCase ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __lowerCamelCase , __lowerCamelCase ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__lowerCamelCase , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__lowerCamelCase , __lowerCamelCase ) # simulate with 10000 shots _snake_case = Aer.get_backend('''qasm_simulator''' ) _snake_case = execute(__lowerCamelCase , __lowerCamelCase , shots=1_00_00 ) return job.result().get_counts(__lowerCamelCase ) if __name__ == "__main__": print( F"Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}" )
288
0
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : int = jnp.ones((batch_size, length)) / length return scores def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Any = None a__ : str = 20 a__ : Any = self._get_uniform_logits(batch_size=2 , length=lowercase) # tweak scores to not be uniform anymore a__ : Any = scores.at[1, 5].set((1 / length) + 0.1) # peak, 1st batch a__ : List[Any] = scores.at[1, 10].set((1 / length) - 0.4) # valley, 1st batch # compute softmax a__ : Optional[Any] = jax.nn.softmax(lowercase , axis=-1) a__ : int = FlaxTemperatureLogitsWarper(temperature=0.5) a__ : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=1.3) a__ : Dict = jax.nn.softmax(temp_dist_warper_sharper(lowercase , scores.copy() , cur_len=lowercase) , axis=-1) a__ : List[str] = jax.nn.softmax(temp_dist_warper_smoother(lowercase , scores.copy() , cur_len=lowercase) , axis=-1) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3)) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3)) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max()) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min()) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max()) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min()) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Tuple = None a__ : int = 10 a__ : Optional[int] = 2 # create ramp distribution a__ : Union[str, Any] = np.broadcast_to(np.arange(lowercase)[None, :] , (batch_size, vocab_size)).copy() a__ : Optional[Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size a__ : List[Any] = FlaxTopKLogitsWarper(3) a__ : str = top_k_warp(lowercase , lowercase , cur_len=lowercase) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0]).tolist() , 7 * [True] + 3 * [False]) self.assertListEqual(jnp.isinf(scores[1]).tolist() , 2 * [True] + 3 * [False] + 5 * [True]) # check special case a__ : Tuple = 5 a__ : Union[str, Any] = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3) a__ : Dict = np.broadcast_to(np.arange(lowercase)[None, :] , (batch_size, length)).copy() a__ : Union[str, Any] = top_k_warp_safety_check(lowercase , lowercase , cur_len=lowercase) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1).tolist() , [2, 2]) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Tuple = None a__ : Optional[int] = 10 a__ : Union[str, Any] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) a__ : Union[str, Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]])) a__ : str = FlaxTopPLogitsWarper(0.8) a__ : List[str] = np.exp(top_p_warp(lowercase , lowercase , cur_len=lowercase)) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 a__ : Any = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]) self.assertTrue(np.allclose(lowercase , lowercase , atol=1e-3)) # check edge cases with negative and extreme logits a__ : Union[str, Any] = np.broadcast_to(np.arange(lowercase)[None, :] , (batch_size, vocab_size)).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme a__ : List[str] = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept a__ : List[Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0) a__ : int = top_p_warp(lowercase , lowercase , cur_len=lowercase) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1).tolist() , [3, 2]) def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Dict = 20 a__ : str = 4 a__ : Union[str, Any] = 0 a__ : Union[str, Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase) # check that min length is applied at length 5 a__ : List[str] = ids_tensor((batch_size, 20) , vocab_size=20) a__ : Optional[int] = 5 a__ : Tuple = self._get_uniform_logits(lowercase , lowercase) a__ : Tuple = min_dist_processor(lowercase , lowercase , cur_len=lowercase) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('inf')]) # check that min length is not applied anymore at length 15 a__ : List[Any] = self._get_uniform_logits(lowercase , lowercase) a__ : Optional[Any] = 15 a__ : int = min_dist_processor(lowercase , lowercase , cur_len=lowercase) self.assertFalse(jnp.isinf(lowercase).any()) def __lowercase ( self) -> str: '''simple docstring''' a__ : Dict = 20 a__ : Any = 4 a__ : Dict = 0 a__ : List[str] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase) # check that all scores are -inf except the bos_token_id score a__ : List[Any] = ids_tensor((batch_size, 1) , vocab_size=20) a__ : List[Any] = 1 a__ : int = self._get_uniform_logits(lowercase , lowercase) a__ : Any = logits_processor(lowercase , lowercase , cur_len=lowercase) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]).all()) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0]) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 a__ : List[str] = 3 a__ : List[str] = self._get_uniform_logits(lowercase , lowercase) a__ : Union[str, Any] = logits_processor(lowercase , lowercase , cur_len=lowercase) self.assertFalse(jnp.isinf(lowercase).any()) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = 20 a__ : str = 4 a__ : Union[str, Any] = 0 a__ : Tuple = 5 a__ : Optional[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase) # check that all scores are -inf except the eos_token_id when max_length is reached a__ : str = ids_tensor((batch_size, 4) , vocab_size=20) a__ : Optional[Any] = 4 a__ : Union[str, Any] = self._get_uniform_logits(lowercase , lowercase) a__ : Optional[int] = logits_processor(lowercase , lowercase , cur_len=lowercase) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]).all()) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0]) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached a__ : Tuple = 3 a__ : Any = self._get_uniform_logits(lowercase , lowercase) a__ : Tuple = logits_processor(lowercase , lowercase , cur_len=lowercase) self.assertFalse(jnp.isinf(lowercase).any()) def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Optional[int] = 4 a__ : Optional[Any] = 10 a__ : Tuple = 15 a__ : Optional[Any] = 2 a__ : List[Any] = 1 a__ : List[str] = 15 # dummy input_ids and scores a__ : Optional[Any] = ids_tensor((batch_size, sequence_length) , lowercase) a__ : str = input_ids.copy() a__ : List[Any] = self._get_uniform_logits(lowercase , lowercase) a__ : Optional[int] = scores.copy() # instantiate all dist processors a__ : Dict = FlaxTemperatureLogitsWarper(temperature=0.5) a__ : str = FlaxTopKLogitsWarper(3) a__ : Optional[int] = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors a__ : Optional[int] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase) a__ : Union[str, Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase) a__ : Union[str, Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase) a__ : int = 10 # no processor list a__ : Any = temp_dist_warp(lowercase , lowercase , cur_len=lowercase) a__ : int = top_k_warp(lowercase , lowercase , cur_len=lowercase) a__ : Optional[Any] = top_p_warp(lowercase , lowercase , cur_len=lowercase) a__ : List[Any] = min_dist_proc(lowercase , lowercase , cur_len=lowercase) a__ : str = bos_dist_proc(lowercase , lowercase , cur_len=lowercase) a__ : Optional[int] = eos_dist_proc(lowercase , lowercase , cur_len=lowercase) # with processor list a__ : Dict = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) a__ : List[str] = processor(lowercase , lowercase , cur_len=lowercase) # scores should be equal self.assertTrue(jnp.allclose(lowercase , lowercase , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist()) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : List[str] = 4 a__ : List[Any] = 10 a__ : Tuple = 15 a__ : int = 2 a__ : Any = 1 a__ : Tuple = 15 # dummy input_ids and scores a__ : Optional[int] = ids_tensor((batch_size, sequence_length) , lowercase) a__ : Union[str, Any] = input_ids.copy() a__ : List[Any] = self._get_uniform_logits(lowercase , lowercase) a__ : Optional[int] = scores.copy() # instantiate all dist processors a__ : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=0.5) a__ : int = FlaxTopKLogitsWarper(3) a__ : List[Any] = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors a__ : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase) a__ : int = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase) a__ : str = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase) a__ : Union[str, Any] = 10 # no processor list def run_no_processor_list(lowercase , lowercase , lowercase): a__ : Tuple = temp_dist_warp(lowercase , lowercase , cur_len=lowercase) a__ : Dict = top_k_warp(lowercase , lowercase , cur_len=lowercase) a__ : Optional[Any] = top_p_warp(lowercase , lowercase , cur_len=lowercase) a__ : Optional[int] = min_dist_proc(lowercase , lowercase , cur_len=lowercase) a__ : List[str] = bos_dist_proc(lowercase , lowercase , cur_len=lowercase) a__ : str = eos_dist_proc(lowercase , lowercase , cur_len=lowercase) return scores # with processor list def run_processor_list(lowercase , lowercase , lowercase): a__ : str = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) a__ : Dict = processor(lowercase , lowercase , cur_len=lowercase) return scores a__ : Any = jax.jit(lowercase) a__ : Tuple = jax.jit(lowercase) a__ : Union[str, Any] = jitted_run_no_processor_list(lowercase , lowercase , lowercase) a__ : List[Any] = jitted_run_processor_list(lowercase , lowercase , lowercase) # scores should be equal self.assertTrue(jnp.allclose(lowercase , lowercase , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist())
225
from __future__ import annotations from collections.abc import Callable def A_ ( A__ , A__ , A__ , A__ = 100 , ) -> float: a__ : Dict = x_start a__ : Any = fnc(A__ ) a__ : Optional[int] = 0.0 for _ in range(A__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area a__ : Union[str, Any] = (x_end - x_start) / steps + xa a__ : str = fnc(A__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step a__ : Optional[Any] = xa a__ : Optional[int] = fxa return area if __name__ == "__main__": def A_ ( A__ ) -> List[str]: return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") lowercase : Union[str, Any] = 1_0 while i <= 1_0_0_0_0_0: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 1_0
225
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys lowerCamelCase__ = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") lowerCamelCase__ = ( subprocess.check_output(F"""git diff --diff-filter=d --name-only {fork_point_sha}""".split()).decode("""utf-8""").split() ) lowerCamelCase__ = """|""".join(sys.argv[1:]) lowerCamelCase__ = re.compile(rF"""^({joined_dirs}).*?\.py$""") lowerCamelCase__ = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. SCREAMING_SNAKE_CASE__:Dict = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. SCREAMING_SNAKE_CASE__:Tuple = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. SCREAMING_SNAKE_CASE__:Optional[int] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def _lowerCamelCase( a , a ): __a = len([g for position, g in enumerate(a ) if g == main_target[position]] ) return (item, float(a )) def _lowerCamelCase( a , a ): __a = random.randint(0 , len(a ) - 1 ) __a = parent_a[:random_slice] + parent_a[random_slice:] __a = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _lowerCamelCase( a , a ): __a = list(a ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __a = random.choice(a ) return "".join(a ) def _lowerCamelCase( a , a , a , ): __a = [] # Generate more children proportionally to the fitness score. __a = int(parent_a[1] * 1_0_0 ) + 1 __a = 1_0 if child_n >= 1_0 else child_n for _ in range(a ): __a = population_score[random.randint(0 , a )][0] __a , __a = crossover(parent_a[0] , a ) # Append new string to the population list. pop.append(mutate(a , a ) ) pop.append(mutate(a , a ) ) return pop def _lowerCamelCase( a , a , a = True ): # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: __a = F"{N_POPULATION} must be bigger than {N_SELECTED}" raise ValueError(a ) # Verify that the target contains no genes besides the ones inside genes variable. __a = sorted({c for c in target if c not in genes} ) if not_in_genes_list: __a = F"{not_in_genes_list} is not in genes list, evolution cannot converge" raise ValueError(a ) # Generate random starting population. __a = [] for _ in range(a ): population.append("".join([random.choice(a ) for i in range(len(a ) )] ) ) # Just some logs to know what the algorithms is doing. __a , __a = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(a ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __a = [evaluate(a , a ) for item in population] # Check if there is a matching evolution. __a = sorted(a , key=lambda a : x[1] , reverse=a ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 1_0 == 0: print( F"\nGeneration: {generation}" F"\nTotal Population:{total_population}" F"\nBest score: {population_score[0][1]}" F"\nBest string: {population_score[0][0]}" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __a = population[: int(N_POPULATION / 3 )] population.clear() population.extend(a ) # Normalize population score to be between 0 and 1. __a = [ (item, score / len(a )) for item, score in population_score ] # This is selection for i in range(a ): population.extend(select(population_score[int(a )] , a , a ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(a ) > N_POPULATION: break if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Union[str, Any] = ( """This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!""" ) SCREAMING_SNAKE_CASE__:Any = list( """ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm""" """nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\""" ) SCREAMING_SNAKE_CASE__:str = basic(target_str, genes_list) print( F'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}''' )
353
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a , a , a , ): __a = len(a ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(a ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , a , a , ) def _lowerCamelCase( a ): __a = [] depth_first_search([] , [] , [] , a , a ) # Print all the boards for board in boards: for column in board: print(a ) print("" ) print(len(a ) , "solutions were found." ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
268
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule A_ = {'''processing_wav2vec2_with_lm''': ['''Wav2Vec2ProcessorWithLM''']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
def a ( snake_case__: int = 100 ): '''simple docstring''' lowercase_ = (n * (n + 1) // 2) ** 2 lowercase_ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
30
0
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def A ( a_ ) -> int: if isinstance(__UpperCAmelCase ,collections.abc.Iterable ): return x return (x, x) @require_flax class __A : """simple docstring""" def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" pass def __lowercase ( self ): """simple docstring""" pass def __lowercase ( self ): """simple docstring""" pass def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Tuple =np.abs((a - b) ).max() self.assertLessEqual(lowercase_ , lowercase_ , f'Difference between torch and flax is {diff} (>= {tol}).' ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Any =VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_ , lowercase_ ) __UpperCamelCase : Tuple =FlaxVisionTextDualEncoderModel(lowercase_ ) __UpperCamelCase : List[Any] =model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Tuple =self.get_vision_text_model(lowercase_ , lowercase_ ) __UpperCamelCase : str ={'vision_model': vision_model, 'text_model': text_model} __UpperCamelCase : List[Any] =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_ ) __UpperCamelCase : Optional[Any] =model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Any =self.get_vision_text_model(lowercase_ , lowercase_ ) __UpperCamelCase : Any ={'vision_model': vision_model, 'text_model': text_model} __UpperCamelCase : Tuple =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_ ) __UpperCamelCase : Optional[int] =model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) __UpperCamelCase : int =output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase_ ) __UpperCamelCase : Union[str, Any] =FlaxVisionTextDualEncoderModel.from_pretrained(lowercase_ ) __UpperCamelCase : Optional[Any] =model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) __UpperCamelCase : int =after_output[0] __UpperCamelCase : Optional[int] =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase_ , 1E-3 ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Dict =self.get_vision_text_model(lowercase_ , lowercase_ ) __UpperCamelCase : Union[str, Any] ={'vision_model': vision_model, 'text_model': text_model} __UpperCamelCase : Optional[Any] =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_ ) __UpperCamelCase : List[str] =model( input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ , output_attentions=lowercase_ ) __UpperCamelCase : Dict =output.vision_model_output.attentions self.assertEqual(len(lowercase_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase : Tuple =to_atuple(vision_model.config.image_size ) __UpperCamelCase : Any =to_atuple(vision_model.config.patch_size ) __UpperCamelCase : Optional[Any] =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __UpperCamelCase : Optional[Any] =num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __UpperCamelCase : Tuple =output.text_model_output.attentions self.assertEqual(len(lowercase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" pt_model.to(lowercase_ ) pt_model.eval() # prepare inputs __UpperCamelCase : Union[str, Any] =inputs_dict __UpperCamelCase : List[Any] ={k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): __UpperCamelCase : Tuple =pt_model(**lowercase_ ).to_tuple() __UpperCamelCase : Optional[int] =fx_model(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowercase_ , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowercase_ ) __UpperCamelCase : str =FlaxVisionTextDualEncoderModel.from_pretrained(lowercase_ , from_pt=lowercase_ ) __UpperCamelCase : List[str] =fx_model_loaded(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowercase_ , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowercase_ ) __UpperCamelCase : Union[str, Any] =VisionTextDualEncoderModel.from_pretrained(lowercase_ , from_flax=lowercase_ ) pt_model_loaded.to(lowercase_ ) pt_model_loaded.eval() with torch.no_grad(): __UpperCamelCase : List[Any] =pt_model_loaded(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(lowercase_ , pt_output_loaded.numpy() , 4E-2 ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Any =VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_ , lowercase_ ) __UpperCamelCase : Dict =VisionTextDualEncoderModel(lowercase_ ) __UpperCamelCase : int =FlaxVisionTextDualEncoderModel(lowercase_ ) __UpperCamelCase : List[Any] =convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowercase_ ) __UpperCamelCase : List[str] =fx_state self.check_pt_flax_equivalence(lowercase_ , lowercase_ , lowercase_ ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Tuple =VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_ , lowercase_ ) __UpperCamelCase : int =VisionTextDualEncoderModel(lowercase_ ) __UpperCamelCase : int =FlaxVisionTextDualEncoderModel(lowercase_ ) __UpperCamelCase : Any =load_flax_weights_in_pytorch_model(lowercase_ , fx_model.params ) self.check_pt_flax_equivalence(lowercase_ , lowercase_ , lowercase_ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowercase_ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowercase_ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =self.prepare_config_and_inputs() self.check_save_load(**lowercase_ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowercase_ ) @is_pt_flax_cross_test def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =self.prepare_config_and_inputs() __UpperCamelCase : Tuple =config_inputs_dict.pop('vision_config' ) __UpperCamelCase : Union[str, Any] =config_inputs_dict.pop('text_config' ) __UpperCamelCase : str =config_inputs_dict self.check_equivalence_pt_to_flax(lowercase_ , lowercase_ , lowercase_ ) self.check_equivalence_flax_to_pt(lowercase_ , lowercase_ , lowercase_ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Optional[int] =self.get_pretrained_model_and_inputs() __UpperCamelCase : Tuple =model_a(**lowercase_ ) __UpperCamelCase : List[Any] =outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowercase_ ) __UpperCamelCase : Optional[Any] =FlaxVisionTextDualEncoderModel.from_pretrained(lowercase_ ) __UpperCamelCase : Any =model_a(**lowercase_ ) __UpperCamelCase : Optional[Any] =after_outputs[0] __UpperCamelCase : Dict =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase_ , 1E-5 ) @require_flax class __A ( _lowerCamelCase , unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=lowercase_ , text_from_pt=lowercase_ , ) __UpperCamelCase : Optional[Any] =13 __UpperCamelCase : int =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __UpperCamelCase : List[str] =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __UpperCamelCase : Any =random_attention_mask([batch_size, 4] ) __UpperCamelCase : int ={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : List[str] =FlaxViTModel(lowercase_ ) __UpperCamelCase : List[str] =FlaxBertModel(lowercase_ ) return vision_model, text_model def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Dict =FlaxViTModelTester(self ) __UpperCamelCase : Dict =FlaxBertModelTester(self ) __UpperCamelCase : List[Any] =vit_model_tester.prepare_config_and_inputs() __UpperCamelCase : Optional[int] =bert_model_tester.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase : List[Any] =vision_config_and_inputs __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : int =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class __A ( _lowerCamelCase , unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" __UpperCamelCase : str =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=lowercase_ , text_from_pt=lowercase_ , ) __UpperCamelCase : Dict =13 __UpperCamelCase : Dict =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __UpperCamelCase : int =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __UpperCamelCase : int =random_attention_mask([batch_size, 4] ) __UpperCamelCase : Tuple ={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Dict =FlaxCLIPVisionModel(lowercase_ ) __UpperCamelCase : int =FlaxBertModel(lowercase_ ) return vision_model, text_model def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =FlaxCLIPVisionModelTester(self ) __UpperCamelCase : Union[str, Any] =FlaxBertModelTester(self ) __UpperCamelCase : Any =clip_model_tester.prepare_config_and_inputs() __UpperCamelCase : Tuple =bert_model_tester.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase : Union[str, Any] =vision_config_and_inputs __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Dict =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) __UpperCamelCase : Optional[Any] =VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) __UpperCamelCase : Optional[Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) __UpperCamelCase : List[str] =processor( text=['una foto di un gatto', 'una foto di un cane'] , images=lowercase_ , padding=lowercase_ , return_tensors='np' ) __UpperCamelCase : List[Any] =model(**lowercase_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __UpperCamelCase : int =np.array([[1.2_284_727, 0.3_104_122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , lowercase_ , atol=1E-3 ) )
356
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
245
0
'''simple docstring''' from __future__ import annotations def _A ( A__ ): """simple docstring""" __lowercase = 0.0_0 __lowercase = 0 for resistor in resistors: if resistor <= 0: __lowercase = F"Resistor at index {index} has a negative or zero value!" raise ValueError(A__ ) first_sum += 1 / float(A__ ) index += 1 return 1 / first_sum def _A ( A__ ): """simple docstring""" __lowercase = 0.0_0 __lowercase = 0 for resistor in resistors: sum_r += resistor if resistor < 0: __lowercase = F"Resistor at index {index} has a negative value!" raise ValueError(A__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
104
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL lowerCAmelCase__ = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def _A ( A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__=False , ): """simple docstring""" output_path.parent.mkdir(parents=A__ , exist_ok=A__ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( A__ , A__ , f=output_path.as_posix() , input_names=A__ , output_names=A__ , dynamic_axes=A__ , do_constant_folding=A__ , use_external_data_format=A__ , enable_onnx_checker=A__ , opset_version=A__ , ) else: export( A__ , A__ , f=output_path.as_posix() , input_names=A__ , output_names=A__ , dynamic_axes=A__ , do_constant_folding=A__ , opset_version=A__ , ) @torch.no_grad() def _A ( A__ , A__ , A__ , A__ = False ): """simple docstring""" __lowercase = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __lowercase = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: __lowercase = '''cpu''' __lowercase = Path(A__ ) # VAE DECODER __lowercase = AutoencoderKL.from_pretrained(model_path + '''/vae''' ) __lowercase = vae_decoder.config.latent_channels # forward only through the decoder part __lowercase = vae_decoder.decode onnx_export( A__ , model_args=( torch.randn(1 , A__ , 25 , 25 ).to(device=A__ , dtype=A__ ), False, ) , output_path=output_path / '''vae_decoder''' / '''model.onnx''' , ordered_input_names=['''latent_sample''', '''return_dict'''] , output_names=['''sample'''] , dynamic_axes={ '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=A__ , ) del vae_decoder if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=14, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') lowerCAmelCase__ = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('''SD: Done: ONNX''')
104
1
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets __UpperCamelCase = datasets.logging.get_logger(__name__) __UpperCamelCase = '''\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric", author = "Moosavi, Nafise Sadat and Strube, Michael", booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)", month = aug, year = "2016", address = "Berlin, Germany", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/P16-1060", doi = "10.18653/v1/P16-1060", pages = "632--642", } ''' __UpperCamelCase = '''\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. ''' __UpperCamelCase = ''' Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting \'keep_singletons=False\', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs. min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: \'mentions\': mentions \'muc\': MUC metric [Vilain et al, 1995] \'bcub\': B-cubed [Bagga and Baldwin, 1998] \'ceafe\': CEAFe [Luo et al., 2005] \'lea\': LEA [Moosavi and Strube, 2016] \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric(\'coval\') >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\', ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\', ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\', ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\', ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\', ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0} ''' def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False , UpperCAmelCase=False , UpperCAmelCase=True , UpperCAmelCase=False , UpperCAmelCase="dummy_doc" ) -> Any: snake_case_ = {doc: key_lines} snake_case_ = {doc: sys_lines} snake_case_ = {} snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ , snake_case_ = reader.get_doc_mentions(UpperCAmelCase , key_doc_lines[doc] , UpperCAmelCase ) key_singletons_num += singletons_num if NP_only or min_span: snake_case_ = reader.set_annotated_parse_trees(UpperCAmelCase , key_doc_lines[doc] , UpperCAmelCase , UpperCAmelCase ) snake_case_ , snake_case_ = reader.get_doc_mentions(UpperCAmelCase , sys_doc_lines[doc] , UpperCAmelCase ) sys_singletons_num += singletons_num if NP_only or min_span: snake_case_ = reader.set_annotated_parse_trees(UpperCAmelCase , key_doc_lines[doc] , UpperCAmelCase , UpperCAmelCase ) if remove_nested: snake_case_ , snake_case_ = reader.remove_nested_coref_mentions(UpperCAmelCase , UpperCAmelCase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters snake_case_ , snake_case_ = reader.remove_nested_coref_mentions(UpperCAmelCase , UpperCAmelCase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters snake_case_ = reader.get_mention_assignments(UpperCAmelCase , UpperCAmelCase ) snake_case_ = reader.get_mention_assignments(UpperCAmelCase , UpperCAmelCase ) snake_case_ = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( 'Number of removed nested coreferring mentions in the key ' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( 'Number of resulting singleton clusters in the key ' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' 'files, respectively' ) return doc_coref_infos def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Tuple: snake_case_ = get_coref_infos(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) snake_case_ = {} snake_case_ = 0 snake_case_ = 0 for name, metric in metrics: snake_case_ , snake_case_ , snake_case_ = evaluator.evaluate_documents(UpperCAmelCase , UpperCAmelCase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 100:.2f}' , f' Precision: {precision * 100:.2f}' , f' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: snake_case_ = (conll / 3) * 100 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'conll_score': conll} ) return output_scores def UpperCAmelCase ( UpperCAmelCase ) -> Any: snake_case_ = False for line in key_lines: if not line.startswith('#' ): if len(line.split() ) > 6: snake_case_ = line.split()[5] if not parse_col == "-": snake_case_ = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase ( datasets.Metric ): def a_ ( self) -> int: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string')), 'references': datasets.Sequence(datasets.Value('string')), }), codebase_urls=['https://github.com/ns-moosavi/coval'], reference_urls=[ 'https://github.com/ns-moosavi/coval', 'https://www.aclweb.org/anthology/P16-1060', 'http://www.conll.cemantix.org/2012/data.html', ], ) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__=True, lowerCAmelCase__=False, lowerCAmelCase__=False, lowerCAmelCase__=False) -> Dict: snake_case_ = [ ('mentions', evaluator.mentions), ('muc', evaluator.muc), ('bcub', evaluator.b_cubed), ('ceafe', evaluator.ceafe), ('lea', evaluator.lea), ] if min_span: snake_case_ = util.check_gold_parse_annotation(lowerCAmelCase__) if not has_gold_parse: raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" snake_case_ = evaluate( key_lines=lowerCAmelCase__, sys_lines=lowerCAmelCase__, metrics=lowerCAmelCase__, NP_only=lowerCAmelCase__, remove_nested=lowerCAmelCase__, keep_singletons=lowerCAmelCase__, min_span=lowerCAmelCase__, ) return score
312
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=1 ) -> Optional[Any]: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=0 ) -> Dict: snake_case_ = [] for old_item in old_list: snake_case_ = old_item.replace('in_layers.0' , 'norm1' ) snake_case_ = new_item.replace('in_layers.2' , 'conv1' ) snake_case_ = new_item.replace('out_layers.0' , 'norm2' ) snake_case_ = new_item.replace('out_layers.3' , 'conv2' ) snake_case_ = new_item.replace('emb_layers.1' , 'time_emb_proj' ) snake_case_ = new_item.replace('skip_connection' , 'conv_shortcut' ) snake_case_ = shave_segments(UpperCAmelCase , n_shave_prefix_segments=UpperCAmelCase ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=0 ) -> Union[str, Any]: snake_case_ = [] for old_item in old_list: snake_case_ = old_item snake_case_ = new_item.replace('norm.weight' , 'group_norm.weight' ) snake_case_ = new_item.replace('norm.bias' , 'group_norm.bias' ) snake_case_ = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) snake_case_ = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) snake_case_ = shave_segments(UpperCAmelCase , n_shave_prefix_segments=UpperCAmelCase ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None ) -> Optional[Any]: assert isinstance(UpperCAmelCase , UpperCAmelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): snake_case_ = old_checkpoint[path] snake_case_ = old_tensor.shape[0] // 3 snake_case_ = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) snake_case_ = old_tensor.shape[0] // config['num_head_channels'] // 3 snake_case_ = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) snake_case_ , snake_case_ , snake_case_ = old_tensor.split(channels // num_heads , dim=1 ) snake_case_ = query.reshape(UpperCAmelCase ) snake_case_ = key.reshape(UpperCAmelCase ) snake_case_ = value.reshape(UpperCAmelCase ) for path in paths: snake_case_ = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here snake_case_ = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) snake_case_ = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) snake_case_ = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: snake_case_ = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: snake_case_ = old_checkpoint[path['old']][:, :, 0] else: snake_case_ = old_checkpoint[path['old']] def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> List[Any]: snake_case_ = {} snake_case_ = checkpoint['time_embed.0.weight'] snake_case_ = checkpoint['time_embed.0.bias'] snake_case_ = checkpoint['time_embed.2.weight'] snake_case_ = checkpoint['time_embed.2.bias'] snake_case_ = checkpoint['input_blocks.0.0.weight'] snake_case_ = checkpoint['input_blocks.0.0.bias'] snake_case_ = checkpoint['out.0.weight'] snake_case_ = checkpoint['out.0.bias'] snake_case_ = checkpoint['out.2.weight'] snake_case_ = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only snake_case_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) snake_case_ = { layer_id: [key for key in checkpoint if f'input_blocks.{layer_id}' in key] for layer_id in range(UpperCAmelCase ) } # Retrieves the keys for the middle blocks only snake_case_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) snake_case_ = { layer_id: [key for key in checkpoint if f'middle_block.{layer_id}' in key] for layer_id in range(UpperCAmelCase ) } # Retrieves the keys for the output blocks only snake_case_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) snake_case_ = { layer_id: [key for key in checkpoint if f'output_blocks.{layer_id}' in key] for layer_id in range(UpperCAmelCase ) } for i in range(1 , UpperCAmelCase ): snake_case_ = (i - 1) // (config['num_res_blocks'] + 1) snake_case_ = (i - 1) % (config['num_res_blocks'] + 1) snake_case_ = [key for key in input_blocks[i] if f'input_blocks.{i}.0' in key] snake_case_ = [key for key in input_blocks[i] if f'input_blocks.{i}.1' in key] if f'input_blocks.{i}.0.op.weight' in checkpoint: snake_case_ = checkpoint[ f'input_blocks.{i}.0.op.weight' ] snake_case_ = checkpoint[ f'input_blocks.{i}.0.op.bias' ] continue snake_case_ = renew_resnet_paths(UpperCAmelCase ) snake_case_ = {'old': f'input_blocks.{i}.0', 'new': f'down_blocks.{block_id}.resnets.{layer_in_block_id}'} snake_case_ = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , additional_replacements=[meta_path, resnet_op] , config=UpperCAmelCase ) if len(UpperCAmelCase ): snake_case_ = renew_attention_paths(UpperCAmelCase ) snake_case_ = { 'old': f'input_blocks.{i}.1', 'new': f'down_blocks.{block_id}.attentions.{layer_in_block_id}', } snake_case_ = { f'input_blocks.{i}.1.qkv.bias': { 'key': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', 'query': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', 'value': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'input_blocks.{i}.1.qkv.weight': { 'key': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', 'query': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', 'value': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , additional_replacements=[meta_path] , attention_paths_to_split=UpperCAmelCase , config=UpperCAmelCase , ) snake_case_ = middle_blocks[0] snake_case_ = middle_blocks[1] snake_case_ = middle_blocks[2] snake_case_ = renew_resnet_paths(UpperCAmelCase ) assign_to_checkpoint(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , config=UpperCAmelCase ) snake_case_ = renew_resnet_paths(UpperCAmelCase ) assign_to_checkpoint(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , config=UpperCAmelCase ) snake_case_ = renew_attention_paths(UpperCAmelCase ) snake_case_ = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , attention_paths_to_split=UpperCAmelCase , config=UpperCAmelCase ) for i in range(UpperCAmelCase ): snake_case_ = i // (config['num_res_blocks'] + 1) snake_case_ = i % (config['num_res_blocks'] + 1) snake_case_ = [shave_segments(UpperCAmelCase , 2 ) for name in output_blocks[i]] snake_case_ = {} for layer in output_block_layers: snake_case_ , snake_case_ = layer.split('.' )[0], shave_segments(UpperCAmelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(UpperCAmelCase ) else: snake_case_ = [layer_name] if len(UpperCAmelCase ) > 1: snake_case_ = [key for key in output_blocks[i] if f'output_blocks.{i}.0' in key] snake_case_ = [key for key in output_blocks[i] if f'output_blocks.{i}.1' in key] snake_case_ = renew_resnet_paths(UpperCAmelCase ) snake_case_ = renew_resnet_paths(UpperCAmelCase ) snake_case_ = {'old': f'output_blocks.{i}.0', 'new': f'up_blocks.{block_id}.resnets.{layer_in_block_id}'} assign_to_checkpoint(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , additional_replacements=[meta_path] , config=UpperCAmelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): snake_case_ = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) snake_case_ = checkpoint[ f'output_blocks.{i}.{index}.conv.weight' ] snake_case_ = checkpoint[ f'output_blocks.{i}.{index}.conv.bias' ] # Clear attentions as they have been attributed above. if len(UpperCAmelCase ) == 2: snake_case_ = [] if len(UpperCAmelCase ): snake_case_ = renew_attention_paths(UpperCAmelCase ) snake_case_ = { 'old': f'output_blocks.{i}.1', 'new': f'up_blocks.{block_id}.attentions.{layer_in_block_id}', } snake_case_ = { f'output_blocks.{i}.1.qkv.bias': { 'key': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', 'query': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', 'value': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'output_blocks.{i}.1.qkv.weight': { 'key': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', 'query': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', 'value': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=UpperCAmelCase , ) else: snake_case_ = renew_resnet_paths(UpperCAmelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: snake_case_ = '.'.join(['output_blocks', str(UpperCAmelCase ), path['old']] ) snake_case_ = '.'.join(['up_blocks', str(UpperCAmelCase ), 'resnets', str(UpperCAmelCase ), path['new']] ) snake_case_ = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __UpperCamelCase = parser.parse_args() __UpperCamelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __UpperCamelCase = json.loads(f.read()) __UpperCamelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __UpperCamelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __UpperCamelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __UpperCamelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __UpperCamelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
312
1
"""simple docstring""" def _lowerCAmelCase ( lowercase_ , lowercase_ ): return int((input_a, input_a).count(0 ) != 0 ) def _lowerCAmelCase ( ): assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
78
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 __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
0
'''simple docstring''' import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Dict ) -> Any: __magic_name__ : List[str] = 0 @slow def __lowerCAmelCase ( self : List[str] ) -> Optional[Any]: for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): __magic_name__ : List[Any] = AutoTokenizer.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(_A ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): __magic_name__ : Dict = AutoTokenizer.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(_A ) , 0 ) def __lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: __magic_name__ : Tuple = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: __magic_name__ : Dict = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: __magic_name__ : List[Any] = AutoConfig.from_pretrained(_A ) self.assertIsInstance(_A , _A ) # Check that tokenizer_type ≠ model_type __magic_name__ : int = AutoTokenizer.from_pretrained(_A , config=_A ) self.assertIsInstance(_A , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCAmelCase ( self : List[str] ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('./tests/fixtures/vocab.txt' , os.path.join(_A , 'vocab.txt' ) ) __magic_name__ : List[Any] = AutoTokenizer.from_pretrained(_A , tokenizer_type='bert' , use_fast=_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('./tests/fixtures/vocab.json' , os.path.join(_A , 'vocab.json' ) ) shutil.copy('./tests/fixtures/merges.txt' , os.path.join(_A , 'merges.txt' ) ) __magic_name__ : int = AutoTokenizer.from_pretrained(_A , tokenizer_type='gpt2' , use_fast=_A ) self.assertIsInstance(_A , _A ) @require_tokenizers def __lowerCAmelCase ( self : int ) -> Any: with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('./tests/fixtures/vocab.txt' , os.path.join(_A , 'vocab.txt' ) ) __magic_name__ : Union[str, Any] = AutoTokenizer.from_pretrained(_A , tokenizer_type='bert' ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('./tests/fixtures/vocab.json' , os.path.join(_A , 'vocab.json' ) ) shutil.copy('./tests/fixtures/merges.txt' , os.path.join(_A , 'merges.txt' ) ) __magic_name__ : Union[str, Any] = AutoTokenizer.from_pretrained(_A , tokenizer_type='gpt2' ) self.assertIsInstance(_A , _A ) def __lowerCAmelCase ( self : List[Any] ) -> List[str]: with pytest.raises(_A ): AutoTokenizer.from_pretrained('./' , tokenizer_type='xxx' ) @require_tokenizers def __lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: __magic_name__ : List[str] = tokenizer_class.from_pretrained('wietsedv/bert-base-dutch-cased' ) self.assertIsInstance(_A , (BertTokenizer, BertTokenizerFast) ) if isinstance(_A , _A ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , _A ) else: self.assertEqual(tokenizer.do_lower_case , _A ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def __lowerCAmelCase ( self : Tuple ) -> Dict: for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( _A , 'julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier' , ): __magic_name__ : Optional[int] = tokenizer_class.from_pretrained('julien-c/herlolip-not-exists' ) def __lowerCAmelCase ( self : str ) -> Any: # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai __magic_name__ : List[Any] = TOKENIZER_MAPPING.values() __magic_name__ : Union[str, Any] = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(_A ) @require_tokenizers def __lowerCAmelCase ( self : Union[str, Any] ) -> List[str]: self.assertIsInstance(AutoTokenizer.from_pretrained('bert-base-cased' , use_fast=_A ) , _A ) self.assertIsInstance(AutoTokenizer.from_pretrained('bert-base-cased' ) , _A ) @require_tokenizers def __lowerCAmelCase ( self : str ) -> List[str]: __magic_name__ : str = AutoTokenizer.from_pretrained('distilbert-base-uncased' , do_lower_case=_A ) __magic_name__ : List[Any] = 'Hello, world. How are you?' __magic_name__ : Tuple = tokenizer.tokenize(_A ) self.assertEqual('[UNK]' , tokens[0] ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained('microsoft/mpnet-base' , do_lower_case=_A ) __magic_name__ : str = tokenizer.tokenize(_A ) self.assertEqual('[UNK]' , tokens[0] ) @require_tokenizers def __lowerCAmelCase ( self : Tuple ) -> List[Any]: __magic_name__ : str = AutoTokenizer.from_pretrained('robot-test/dummy-tokenizer-fast-with-model-config' ) self.assertEqual(type(_A ) , _A ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 30000 ) self.assertEqual(tokenizer.unk_token , '[UNK]' ) self.assertEqual(tokenizer.padding_side , 'right' ) self.assertEqual(tokenizer.truncation_side , 'right' ) def __lowerCAmelCase ( self : Any ) -> Optional[Any]: __magic_name__ : Tuple = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def __lowerCAmelCase ( self : Dict ) -> int: __magic_name__ : List[str] = AutoTokenizer.from_pretrained('ctrl' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(_A , _A ) def __lowerCAmelCase ( self : Optional[int] ) -> Any: # Check we can load the tokenizer config of an online model. __magic_name__ : List[Any] = get_tokenizer_config('bert-base-cased' ) __magic_name__ : Dict = config.pop('_commit_hash' , _A ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(_A , {'do_lower_case': False} ) # This model does not have a tokenizer_config so we get back an empty dict. __magic_name__ : Optional[Any] = get_tokenizer_config(_A ) self.assertDictEqual(_A , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. __magic_name__ : List[str] = AutoTokenizer.from_pretrained(_A ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : List[Any] = get_tokenizer_config(_A ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['tokenizer_class'] , 'BertTokenizer' ) def __lowerCAmelCase ( self : str ) -> List[Any]: try: AutoConfig.register('custom' , _A ) AutoTokenizer.register(_A , slow_tokenizer_class=_A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): AutoTokenizer.register(_A , slow_tokenizer_class=_A ) __magic_name__ : Tuple = CustomTokenizer.from_pretrained(_A ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : Optional[int] = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def __lowerCAmelCase ( self : Any ) -> Any: try: AutoConfig.register('custom' , _A ) # Can register in two steps AutoTokenizer.register(_A , slow_tokenizer_class=_A ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(_A , fast_tokenizer_class=_A ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( _A , slow_tokenizer_class=_A , fast_tokenizer_class=_A ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): AutoTokenizer.register(_A , fast_tokenizer_class=_A ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Tuple = BertTokenizerFast.from_pretrained(_A ) bert_tokenizer.save_pretrained(_A ) __magic_name__ : Tuple = CustomTokenizerFast.from_pretrained(_A ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : Union[str, Any] = AutoTokenizer.from_pretrained(_A ) self.assertIsInstance(_A , _A ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained(_A , use_fast=_A ) self.assertIsInstance(_A , _A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_A ): __magic_name__ : str = AutoTokenizer.from_pretrained('hf-internal-testing/test_dynamic_tokenizer' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_A ): __magic_name__ : Optional[int] = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A ) __magic_name__ : Optional[Any] = AutoTokenizer.from_pretrained('hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : int = AutoTokenizer.from_pretrained(_A , trust_remote_code=_A ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , 'NewTokenizerFast' ) # Test we can also load the slow version __magic_name__ : List[Any] = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A , use_fast=_A ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_A ) __magic_name__ : Tuple = AutoTokenizer.from_pretrained(_A , trust_remote_code=_A , use_fast=_A ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , 'NewTokenizer' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , 'NewTokenizer' ) @require_tokenizers def __lowerCAmelCase ( self : List[Any] ) -> Union[str, Any]: class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : Union[str, Any] = False class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : str = NewTokenizer A_ : str = False try: AutoConfig.register('custom' , _A ) AutoTokenizer.register(_A , slow_tokenizer_class=_A ) AutoTokenizer.register(_A , fast_tokenizer_class=_A ) # If remote code is not set, the default is to use local __magic_name__ : Any = AutoTokenizer.from_pretrained('hf-internal-testing/test_dynamic_tokenizer' ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) self.assertFalse(tokenizer.special_attribute_present ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained('hf-internal-testing/test_dynamic_tokenizer' , use_fast=_A ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. __magic_name__ : List[str] = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) self.assertFalse(tokenizer.special_attribute_present ) __magic_name__ : Tuple = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A , use_fast=_A ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub __magic_name__ : Dict = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) self.assertTrue(tokenizer.special_attribute_present ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer' , trust_remote_code=_A , use_fast=_A ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[str] ) -> List[Any]: __magic_name__ : Dict = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer_legacy' , trust_remote_code=_A ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) # Test we can also load the slow version __magic_name__ : int = AutoTokenizer.from_pretrained( 'hf-internal-testing/test_dynamic_tokenizer_legacy' , trust_remote_code=_A , use_fast=_A ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) else: self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: with self.assertRaisesRegex( _A , 'bert-base is not a local folder and is not a valid model identifier' ): __magic_name__ : str = AutoTokenizer.from_pretrained('bert-base' ) def __lowerCAmelCase ( self : Tuple ) -> List[Any]: with self.assertRaisesRegex( _A , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): __magic_name__ : int = AutoTokenizer.from_pretrained(_A , revision='aaaaaa' ) def __lowerCAmelCase ( self : List[Any] ) -> List[str]: # Make sure we have cached the tokenizer. __magic_name__ : str = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) with RequestCounter() as counter: __magic_name__ : str = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
275
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor lowerCAmelCase :Optional[Any] = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCamelCase ( lowerCAmelCase : Tuple ): """simple docstring""" if isinstance(lowerCAmelCase , torch.Tensor ): return image elif isinstance(lowerCAmelCase , PIL.Image.Image ): __magic_name__ : List[Any] = [image] __magic_name__ : List[Any] = [trans(img.convert('RGB' ) ) for img in image] __magic_name__ : Dict = torch.stack(lowerCAmelCase ) return image class _lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self : Optional[Any] , _A : str , _A : int ) -> Dict: super().__init__() # make sure scheduler can always be converted to DDIM __magic_name__ : Optional[int] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_A , scheduler=_A ) def __lowerCAmelCase ( self : Union[str, Any] , _A : Union[str, Any] ) -> Optional[int]: if strength < 0 or strength > 1: raise ValueError(F'The value of strength should in [0.0, 1.0] but is {strength}' ) def __lowerCAmelCase ( self : Any , _A : List[str] , _A : Optional[Any] , _A : int ) -> List[Any]: # get the original timestep using init_timestep __magic_name__ : Tuple = min(int(num_inference_steps * strength ) , _A ) __magic_name__ : Any = max(num_inference_steps - init_timestep , 0 ) __magic_name__ : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowerCAmelCase ( self : Any , _A : str , _A : Optional[int] , _A : Tuple , _A : List[str] , _A : str , _A : Optional[int]=None ) -> Dict: if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}' ) __magic_name__ : Union[str, Any] = image.to(device=_A , dtype=_A ) if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(_A )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) __magic_name__ : Tuple = init_latents.shape __magic_name__ : Any = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents print('add noise to latents at timestep' , _A ) __magic_name__ : List[str] = self.scheduler.add_noise(_A , _A , _A ) __magic_name__ : List[str] = init_latents return latents @torch.no_grad() def __call__( self : Tuple , _A : Union[torch.FloatTensor, PIL.Image.Image] = None , _A : float = 0.8 , _A : int = 1 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : float = 0.0 , _A : int = 50 , _A : Optional[bool] = None , _A : Optional[str] = "pil" , _A : bool = True , ) -> Union[ImagePipelineOutput, Tuple]: self.check_inputs(_A ) # 2. Preprocess image __magic_name__ : int = preprocess(_A ) # 3. set timesteps self.scheduler.set_timesteps(_A , device=self.device ) __magic_name__ , __magic_name__ : Dict = self.get_timesteps(_A , _A , self.device ) __magic_name__ : Dict = timesteps[:1].repeat(_A ) # 4. Prepare latent variables __magic_name__ : Optional[Any] = self.prepare_latents(_A , _A , _A , self.unet.dtype , self.device , _A ) __magic_name__ : Optional[Any] = latents # 5. Denoising loop for t in self.progress_bar(_A ): # 1. predict noise model_output __magic_name__ : Dict = self.unet(_A , _A ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 __magic_name__ : List[Any] = self.scheduler.step( _A , _A , _A , eta=_A , use_clipped_model_output=_A , generator=_A , ).prev_sample __magic_name__ : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) __magic_name__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __magic_name__ : Dict = self.numpy_to_pil(_A ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_A )
275
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : Union[str, Any] = tempfile.mkdtemp() lowerCAmelCase_ : Optional[Any] = BlipImageProcessor() lowerCAmelCase_ : str = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) lowerCAmelCase_ : Tuple = BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert' ) lowerCAmelCase_ : Optional[Any] = InstructBlipProcessor(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , **SCREAMING_SNAKE_CASE_ : Dict ): return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ).tokenizer def SCREAMING_SNAKE_CASE__ ( self : List[str] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ).image_processor def SCREAMING_SNAKE_CASE__ ( self : Tuple , **SCREAMING_SNAKE_CASE_ : str ): return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ).qformer_tokenizer def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowerCAmelCase_ : List[Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] lowerCAmelCase_ : Dict = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE__ ( self : Any ): lowerCAmelCase_ : Any = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase_ : Any = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCAmelCase_ : Any = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) lowerCAmelCase_ : List[str] = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor.qformer_tokenizer , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): lowerCAmelCase_ : Dict = self.get_image_processor() lowerCAmelCase_ : List[str] = self.get_tokenizer() lowerCAmelCase_ : str = self.get_qformer_tokenizer() lowerCAmelCase_ : Dict = InstructBlipProcessor( tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ , qformer_tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[str] = self.prepare_image_inputs() lowerCAmelCase_ : Optional[int] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='np' ) lowerCAmelCase_ : Union[str, Any] = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowerCAmelCase_ : List[Any] = self.get_image_processor() lowerCAmelCase_ : Any = self.get_tokenizer() lowerCAmelCase_ : Tuple = self.get_qformer_tokenizer() lowerCAmelCase_ : List[Any] = InstructBlipProcessor( tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ , qformer_tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : int = 'lower newer' lowerCAmelCase_ : Optional[int] = processor(text=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : int = tokenizer(SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Optional[int] = qformer_tokenizer(SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['qformer_' + key] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowerCAmelCase_ : Optional[Any] = self.get_image_processor() lowerCAmelCase_ : Any = self.get_tokenizer() lowerCAmelCase_ : Dict = self.get_qformer_tokenizer() lowerCAmelCase_ : List[Any] = InstructBlipProcessor( tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ , qformer_tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : str = 'lower newer' lowerCAmelCase_ : Optional[int] = self.prepare_image_inputs() lowerCAmelCase_ : Optional[Any] = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): lowerCAmelCase_ : Dict = self.get_image_processor() lowerCAmelCase_ : Tuple = self.get_tokenizer() lowerCAmelCase_ : Any = self.get_qformer_tokenizer() lowerCAmelCase_ : Any = InstructBlipProcessor( tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ , qformer_tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase_ : Dict = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Any = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : List[str] = self.get_image_processor() lowerCAmelCase_ : Union[str, Any] = self.get_tokenizer() lowerCAmelCase_ : Dict = self.get_qformer_tokenizer() lowerCAmelCase_ : Dict = InstructBlipProcessor( tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ , qformer_tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Optional[Any] = 'lower newer' lowerCAmelCase_ : List[Any] = self.prepare_image_inputs() lowerCAmelCase_ : Any = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , )
224
"""simple docstring""" import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
224
1
'''simple docstring''' def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" A = len(UpperCAmelCase ) A = sum(UpperCAmelCase ) A = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): A = True for i in range(1 , s + 1 ): A = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): A = dp[i][j - 1] if arr[i - 1] <= j: A = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: A = s - 2 * j break return diff
337
'''simple docstring''' _lowerCamelCase : List[Any] = 'Input must be a string of 8 numbers plus letter' _lowerCamelCase : str = 'TRWAGMYFPDXBNJZSQVHLCKE' def __a ( UpperCAmelCase ) ->bool: """simple docstring""" if not isinstance(UpperCAmelCase , UpperCAmelCase ): A = f"""Expected string as input, found {type(UpperCAmelCase ).__name__}""" raise TypeError(UpperCAmelCase ) A = spanish_id.replace("""-""" , """""" ).upper() if len(UpperCAmelCase ) != 9: raise ValueError(UpperCAmelCase ) try: A = int(spanish_id_clean[0:8] ) A = spanish_id_clean[8] except ValueError as ex: raise ValueError(UpperCAmelCase ) from ex if letter.isdigit(): raise ValueError(UpperCAmelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
337
1
from maths.prime_check import is_prime def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> int: if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): __lowercase = F"""Input value of [number={number}] must be an integer""" raise TypeError(SCREAMING_SNAKE_CASE ) if is_prime(SCREAMING_SNAKE_CASE ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
325
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict ) -> List[str]: if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class A__ ( nn.Module ): def __init__( self : Any , _UpperCAmelCase : nn.Module , _UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" super().__init__() __lowercase = module __lowercase = nn.Sequential( nn.Linear(module.in_features , _UpperCAmelCase , bias=_UpperCAmelCase ) , nn.Linear(_UpperCAmelCase , module.out_features , bias=_UpperCAmelCase ) , ) __lowercase = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=_UpperCAmelCase ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def a__ ( self : str , _UpperCAmelCase : List[str] , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" return self.module(_UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase ) + self.adapter(_UpperCAmelCase ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module lowerCAmelCase__ : int = "bigscience/bloom-1b7" # Constant values lowerCAmelCase__ : Any = 2.109659552692574 lowerCAmelCase__ : str = "Hello my name is" lowerCAmelCase__ : Any = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) lowerCAmelCase__ : List[Any] = 10 def a__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __lowercase = AutoTokenizer.from_pretrained(self.model_name ) class A__ ( lowerCAmelCase__ ): def a__ ( self : Any ) -> Union[str, Any]: """simple docstring""" super().setUp() # Models and tokenizer __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) def a__ ( self : Any ) -> Optional[Any]: """simple docstring""" del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def a__ ( self : str ) -> int: """simple docstring""" __lowercase = self.model_abit.config self.assertTrue(hasattr(_UpperCAmelCase , 'quantization_config' ) ) __lowercase = config.to_dict() __lowercase = config.to_diff_dict() __lowercase = config.to_json_string() def a__ ( self : Dict ) -> Tuple: """simple docstring""" from bitsandbytes.nn import Paramsabit __lowercase = self.model_fpaa.get_memory_footprint() __lowercase = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __lowercase = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def a__ ( self : Tuple ) -> str: """simple docstring""" from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(_UpperCAmelCase , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def a__ ( self : List[str] ) -> str: """simple docstring""" __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) def a__ ( self : Union[str, Any] ) -> str: """simple docstring""" __lowercase = BitsAndBytesConfig() __lowercase = True __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) def a__ ( self : str ) -> List[str]: """simple docstring""" with self.assertRaises(_UpperCAmelCase ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(_UpperCAmelCase ) def a__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __lowercase = BitsAndBytesConfig() with self.assertRaises(_UpperCAmelCase ): __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_UpperCAmelCase , load_in_abit=_UpperCAmelCase , device_map='auto' , bnb_abit_quant_type='nf4' , ) def a__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" with self.assertRaises(_UpperCAmelCase ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.float() with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = self.model_fpaa.to(torch.floataa ) __lowercase = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __lowercase = self.model_fpaa.to('cpu' ) # Check this does not throw an error __lowercase = self.model_fpaa.half() # Check this does not throw an error __lowercase = self.model_fpaa.float() def a__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __lowercase = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=_UpperCAmelCase , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): @classmethod def a__ ( cls : int ) -> Tuple: """simple docstring""" __lowercase = 't5-small' __lowercase = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __lowercase = AutoTokenizer.from_pretrained(cls.model_name ) __lowercase = 'Translate in German: Hello, my dog is cute' def a__ ( self : List[Any] ) -> Dict: """simple docstring""" gc.collect() torch.cuda.empty_cache() def a__ ( self : int ) -> int: """simple docstring""" from transformers import TaForConditionalGeneration __lowercase = TaForConditionalGeneration._keep_in_fpaa_modules __lowercase = None # test with `t5-small` __lowercase = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) # test with `flan-t5-small` __lowercase = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) __lowercase = modules def a__ ( self : str ) -> Optional[Any]: """simple docstring""" import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __lowercase = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) # test with `flan-t5-small` __lowercase = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) class A__ ( lowerCAmelCase__ ): def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" super().setUp() # model_name __lowercase = 'bigscience/bloom-560m' __lowercase = 't5-small' # Different types of model __lowercase = AutoModel.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # Sequence classification model __lowercase = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # CausalLM model __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # Seq2seq model __lowercase = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) def a__ ( self : int ) -> List[str]: """simple docstring""" del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def a__ ( self : Tuple ) -> str: """simple docstring""" from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class A__ ( lowerCAmelCase__ ): def a__ ( self : str ) -> str: """simple docstring""" super().setUp() def a__ ( self : Dict ) -> Any: """simple docstring""" del self.pipe gc.collect() torch.cuda.empty_cache() def a__ ( self : Tuple ) -> int: """simple docstring""" __lowercase = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __lowercase = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class A__ ( lowerCAmelCase__ ): def a__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" super().setUp() def a__ ( self : List[Any] ) -> int: """simple docstring""" __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=_UpperCAmelCase , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __lowercase = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) class A__ ( lowerCAmelCase__ ): def a__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __lowercase = 'facebook/opt-350m' super().setUp() def a__ ( self : Dict ) -> List[str]: """simple docstring""" if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __lowercase = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __lowercase = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(_UpperCAmelCase ) ): __lowercase = LoRALayer(module.q_proj , rank=16 ) __lowercase = LoRALayer(module.k_proj , rank=16 ) __lowercase = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __lowercase = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __lowercase = model.forward(**_UpperCAmelCase ) out.logits.norm().backward() for module in model.modules(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(_UpperCAmelCase , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : Any = "gpt2-xl" lowerCAmelCase__ : str = 3.3191854854152187
325
1
from __future__ import annotations def __a ( lowerCAmelCase_ : list[float] ) -> bool: '''simple docstring''' if len(lowerCAmelCase_ ) < 2: raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" ) if any(i <= 0 for i in nums ): raise ValueError("""All values must be greater than 0""" ) UpperCAmelCase_= nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
364
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal __A = datasets.utils.logging.get_logger(__name__) __A = ['''names''', '''prefix'''] __A = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] __A = ['''encoding_errors''', '''on_bad_lines'''] __A = ['''date_format'''] @dataclass class lowercase ( datasets.BuilderConfig): """simple docstring""" a__ : str = "," a__ : Optional[str] = None a__ : Optional[Union[int, List[int], str]] = "infer" a__ : Optional[List[str]] = None a__ : Optional[List[str]] = None a__ : Optional[Union[int, str, List[int], List[str]]] = None a__ : Optional[Union[List[int], List[str]]] = None a__ : Optional[str] = None a__ : bool = True a__ : Optional[Literal["c", "python", "pyarrow"]] = None a__ : Dict[Union[int, str], Callable[[Any], Any]] = None a__ : Optional[list] = None a__ : Optional[list] = None a__ : bool = False a__ : Optional[Union[int, List[int]]] = None a__ : Optional[int] = None a__ : Optional[Union[str, List[str]]] = None a__ : bool = True a__ : bool = True a__ : bool = False a__ : bool = True a__ : Optional[str] = None a__ : str = "." a__ : Optional[str] = None a__ : str = '"' a__ : int = 0 a__ : Optional[str] = None a__ : Optional[str] = None a__ : Optional[str] = None a__ : Optional[str] = None a__ : bool = True a__ : bool = True a__ : int = 0 a__ : bool = True a__ : bool = False a__ : Optional[str] = None a__ : int = 1_0000 a__ : Optional[datasets.Features] = None a__ : Optional[str] = "strict" a__ : Literal["error", "warn", "skip"] = "error" a__ : Optional[str] = None def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: if self.delimiter is not None: UpperCAmelCase_= self.delimiter if self.column_names is not None: UpperCAmelCase_= self.column_names @property def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: UpperCAmelCase_= { """sep""": self.sep, """header""": self.header, """names""": self.names, """index_col""": self.index_col, """usecols""": self.usecols, """prefix""": self.prefix, """mangle_dupe_cols""": self.mangle_dupe_cols, """engine""": self.engine, """converters""": self.converters, """true_values""": self.true_values, """false_values""": self.false_values, """skipinitialspace""": self.skipinitialspace, """skiprows""": self.skiprows, """nrows""": self.nrows, """na_values""": self.na_values, """keep_default_na""": self.keep_default_na, """na_filter""": self.na_filter, """verbose""": self.verbose, """skip_blank_lines""": self.skip_blank_lines, """thousands""": self.thousands, """decimal""": self.decimal, """lineterminator""": self.lineterminator, """quotechar""": self.quotechar, """quoting""": self.quoting, """escapechar""": self.escapechar, """comment""": self.comment, """encoding""": self.encoding, """dialect""": self.dialect, """error_bad_lines""": self.error_bad_lines, """warn_bad_lines""": self.warn_bad_lines, """skipfooter""": self.skipfooter, """doublequote""": self.doublequote, """memory_map""": self.memory_map, """float_precision""": self.float_precision, """chunksize""": self.chunksize, """encoding_errors""": self.encoding_errors, """on_bad_lines""": self.on_bad_lines, """date_format""": self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , __UpperCAmelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowercase ( datasets.ArrowBasedBuilder): """simple docstring""" a__ : int = CsvConfig def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : Any , __UpperCAmelCase : Dict ) -> Optional[int]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) UpperCAmelCase_= dl_manager.download_and_extract(self.config.data_files ) if isinstance(__UpperCAmelCase , (str, list, tuple) ): UpperCAmelCase_= data_files if isinstance(__UpperCAmelCase , __UpperCAmelCase ): UpperCAmelCase_= [files] UpperCAmelCase_= [dl_manager.iter_files(__UpperCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] UpperCAmelCase_= [] for split_name, files in data_files.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): UpperCAmelCase_= [files] UpperCAmelCase_= [dl_manager.iter_files(__UpperCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=__UpperCAmelCase , gen_kwargs={"""files""": files} ) ) return splits def _SCREAMING_SNAKE_CASE ( self : Tuple , __UpperCAmelCase : pa.Table ) -> pa.Table: if self.config.features is not None: UpperCAmelCase_= self.config.features.arrow_schema if all(not require_storage_cast(__UpperCAmelCase ) for feature in self.config.features.values() ): # cheaper cast UpperCAmelCase_= pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=__UpperCAmelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCAmelCase_= table_cast(__UpperCAmelCase , __UpperCAmelCase ) return pa_table def _SCREAMING_SNAKE_CASE ( self : Any , __UpperCAmelCase : List[Any] ) -> List[str]: UpperCAmelCase_= self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCAmelCase_= ( { name: dtype.to_pandas_dtype() if not require_storage_cast(__UpperCAmelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase ) ): UpperCAmelCase_= pd.read_csv(__UpperCAmelCase , iterator=__UpperCAmelCase , dtype=__UpperCAmelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(__UpperCAmelCase ): UpperCAmelCase_= pa.Table.from_pandas(__UpperCAmelCase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__UpperCAmelCase ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(__UpperCAmelCase )}: {e}""" ) raise
277
0
'''simple docstring''' from __future__ import annotations def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> list[str]: '''simple docstring''' if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) _a = number_of_bytes // partitions _a = [] for i in range(lowerCAmelCase__ ): _a = i * bytes_per_partition + 1 _a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'{start_bytes}-{end_bytes}' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
168
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) a_ : str = _symbol_database.Default() a_ : Union[str, Any] = _descriptor_pool.Default().AddSerializedFile( B"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03" ) a_ : List[Any] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals) if _descriptor._USE_C_DESCRIPTORS is False: a_ : List[str] = None a_ : Tuple = B"H\003" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" a_ : Optional[int] = 4_5 a_ : Union[str, Any] = 1_5_8_1 a_ : List[Any] = 1_5_1_7 a_ : str = 1_5_7_0 a_ : List[Any] = 1_5_8_4 a_ : str = 1_7_9_3 a_ : List[str] = 1_7_9_5 a_ : Any = 1_9_1_6 a_ : List[str] = 1_8_6_4 a_ : Optional[Any] = 1_9_0_5 a_ : int = 1_9_1_9 a_ : int = 2_4_2_9 a_ : Dict = 2_2_0_8 a_ : Any = 2_4_1_8 a_ : Union[str, Any] = 2_3_2_3 a_ : str = 2_4_0_7 # @@protoc_insertion_point(module_scope)
168
1
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , _a ): __magic_name__ : Any = str(id_ ) __magic_name__ : Any = None __magic_name__ : List[str] = None __magic_name__ : str = [] __magic_name__ : str = {} # {vertex:distance} def __lt__( self , _a ): return self.key < other.key def __repr__( self ): return self.id def SCREAMING_SNAKE_CASE ( self , _a ): self.neighbors.append(_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Any = weight def lowerCAmelCase_ ( _snake_case : str , _snake_case : Optional[Any] , _snake_case : int , _snake_case : str ) -> Optional[Any]: '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _snake_case ) graph[b - 1].add_edge(graph[a - 1] , _snake_case ) def lowerCAmelCase_ ( _snake_case : list , _snake_case : Vertex ) -> list: '''simple docstring''' __magic_name__ : Optional[int] = [] for u in graph: __magic_name__ : Optional[int] = math.inf __magic_name__ : Tuple = None __magic_name__ : int = 0 __magic_name__ : Tuple = graph[:] while q: __magic_name__ : Optional[int] = min(_snake_case ) q.remove(_snake_case ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): __magic_name__ : Dict = u __magic_name__ : str = u.edges[v.id] for i in range(1 , len(_snake_case ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def lowerCAmelCase_ ( _snake_case : list , _snake_case : Vertex ) -> Iterator[tuple]: '''simple docstring''' for u in graph: __magic_name__ : Optional[int] = math.inf __magic_name__ : str = None __magic_name__ : List[Any] = 0 __magic_name__ : Dict = list(_snake_case ) hq.heapify(_snake_case ) while h: __magic_name__ : Optional[int] = hq.heappop(_snake_case ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): __magic_name__ : List[str] = u __magic_name__ : Dict = u.edges[v.id] hq.heapify(_snake_case ) for i in range(1 , len(_snake_case ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
41
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Optional[Any] = logging.get_logger(__name__) snake_case : Union[str, Any] = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class _snake_case ( snake_case ): UpperCamelCase__ = 'transfo-xl' UpperCamelCase__ = ['mems'] UpperCamelCase__ = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _a=267_735 , _a=[20_000, 40_000, 200_000] , _a=1_024 , _a=1_024 , _a=16 , _a=64 , _a=4_096 , _a=4 , _a=False , _a=18 , _a=1_600 , _a=1_000 , _a=True , _a=True , _a=0 , _a=-1 , _a=True , _a=0.1 , _a=0.0 , _a=True , _a="normal" , _a=0.01 , _a=0.01 , _a=0.02 , _a=1e-5 , _a=0 , **_a , ): __magic_name__ : List[Any] = vocab_size __magic_name__ : Dict = [] self.cutoffs.extend(_a ) if proj_share_all_but_first: __magic_name__ : List[str] = [False] + [True] * len(self.cutoffs ) else: __magic_name__ : Optional[Any] = [False] + [False] * len(self.cutoffs ) __magic_name__ : Optional[int] = d_model __magic_name__ : str = d_embed __magic_name__ : Optional[Any] = d_head __magic_name__ : Optional[int] = d_inner __magic_name__ : List[str] = div_val __magic_name__ : List[str] = pre_lnorm __magic_name__ : Union[str, Any] = n_layer __magic_name__ : Optional[int] = n_head __magic_name__ : str = mem_len __magic_name__ : int = same_length __magic_name__ : Dict = attn_type __magic_name__ : int = clamp_len __magic_name__ : Optional[int] = sample_softmax __magic_name__ : List[Any] = adaptive __magic_name__ : Optional[int] = dropout __magic_name__ : Optional[int] = dropatt __magic_name__ : Optional[Any] = untie_r __magic_name__ : List[str] = init __magic_name__ : Any = init_range __magic_name__ : Optional[int] = proj_init_std __magic_name__ : List[Any] = init_std __magic_name__ : List[Any] = layer_norm_epsilon super().__init__(eos_token_id=_a , **_a ) @property def SCREAMING_SNAKE_CASE ( self ): # Message copied from Transformer-XL documentation logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def SCREAMING_SNAKE_CASE ( self , _a ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
41
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self) ->int: a_ = tempfile.mkdtemp() # fmt: off a_ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a_ = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase)))) a_ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a_ = {"unk_token": "<unk>"} a_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) a_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as fp: fp.write(json.dumps(__UpperCAmelCase) + "\n") with open(self.merges_file , "w" , encoding="utf-8") as fp: fp.write("\n".join(__UpperCAmelCase)) a_ = { "do_resize": True, "size": 20, "do_center_crop": True, "crop_size": 18, "do_normalize": True, "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073], "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711], } a_ = os.path.join(self.tmpdirname , __UpperCAmelCase) with open(self.image_processor_file , "w" , encoding="utf-8") as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase) def UpperCAmelCase__ ( self , **__UpperCAmelCase) ->str: return CLIPTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase) def UpperCAmelCase__ ( self , **__UpperCAmelCase) ->Any: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCAmelCase) def UpperCAmelCase__ ( self , **__UpperCAmelCase) ->Union[str, Any]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Tuple: shutil.rmtree(self.tmpdirname) def UpperCAmelCase__ ( self) ->List[str]: a_ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta)] a_ = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1)) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self) ->Tuple: a_ = self.get_tokenizer() a_ = self.get_rust_tokenizer() a_ = self.get_image_processor() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) processor_slow.save_pretrained(self.tmpdirname) a_ = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase) a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) processor_fast.save_pretrained(self.tmpdirname) a_ = CLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , __UpperCAmelCase) self.assertIsInstance(processor_fast.tokenizer , __UpperCAmelCase) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , __UpperCAmelCase) self.assertIsInstance(processor_fast.image_processor , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->Union[str, Any]: a_ = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) a_ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") a_ = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0) a_ = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__UpperCAmelCase , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->Tuple: a_ = self.get_image_processor() a_ = self.get_tokenizer() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) a_ = self.prepare_image_inputs() a_ = image_processor(__UpperCAmelCase , return_tensors="np") a_ = processor(images=__UpperCAmelCase , return_tensors="np") for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2) def UpperCAmelCase__ ( self) ->Union[str, Any]: a_ = self.get_image_processor() a_ = self.get_tokenizer() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) a_ = "lower newer" a_ = processor(text=__UpperCAmelCase) a_ = tokenizer(__UpperCAmelCase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def UpperCAmelCase__ ( self) ->List[str]: a_ = self.get_image_processor() a_ = self.get_tokenizer() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) a_ = "lower newer" a_ = self.prepare_image_inputs() a_ = processor(text=__UpperCAmelCase , images=__UpperCAmelCase) self.assertListEqual(list(inputs.keys()) , ["input_ids", "attention_mask", "pixel_values"]) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase): processor() def UpperCAmelCase__ ( self) ->str: a_ = self.get_image_processor() a_ = self.get_tokenizer() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) a_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a_ = processor.batch_decode(__UpperCAmelCase) a_ = tokenizer.batch_decode(__UpperCAmelCase) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->Union[str, Any]: a_ = self.get_image_processor() a_ = self.get_tokenizer() a_ = CLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase) a_ = "lower newer" a_ = self.prepare_image_inputs() a_ = processor(text=__UpperCAmelCase , images=__UpperCAmelCase) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
243
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ( SCREAMING_SNAKE_CASE_ ): a_ : List[str] = """""" a_ : Dict = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) ->Optional[int]: super().__init__(self , **__UpperCAmelCase) a_ = repo_info a_ = token a_ = None def UpperCAmelCase__ ( self) ->Tuple: if self.dir_cache is None: a_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes a_ = { "name": hf_file.rfilename, "size": None, "type": "file", } self.dir_cache.update( { str(__UpperCAmelCase): {"name": str(__UpperCAmelCase), "size": None, "type": "directory"} for d in list(PurePosixPath(hf_file.rfilename).parents)[:-1] }) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase = "rb" , **__UpperCAmelCase , ) ->List[Any]: if not isinstance(self.repo_info , __UpperCAmelCase): raise NotImplementedError(F'''Open is only implemented for dataset repositories, but got {self.repo_info}''') a_ = hf_hub_url(self.repo_info.id , __UpperCAmelCase , revision=self.repo_info.sha) return fsspec.open( __UpperCAmelCase , mode=__UpperCAmelCase , headers=get_authentication_headers_for_url(__UpperCAmelCase , use_auth_token=self.token) , client_kwargs={"trust_env": True} , ).open() def UpperCAmelCase__ ( self , __UpperCAmelCase , **__UpperCAmelCase) ->int: self._get_dirs() a_ = self._strip_protocol(__UpperCAmelCase) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(__UpperCAmelCase) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase=False , **__UpperCAmelCase) ->List[Any]: self._get_dirs() a_ = PurePosixPath(path.strip("/")) a_ = {} for p, f in self.dir_cache.items(): a_ = PurePosixPath(p.strip("/")) a_ = p.parent if root == path: a_ = f a_ = list(paths.values()) if detail: return out else: return sorted(f["name"] for f in out)
243
1
'''simple docstring''' from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def lowerCamelCase ( UpperCAmelCase__ : Any ) -> int: if isinstance(UpperCAmelCase__ , collections.abc.Iterable ): return x return (x, x) @require_tf class __magic_name__ : def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Union[str, Any] ): pass def SCREAMING_SNAKE_CASE_ ( self : Dict ): pass def SCREAMING_SNAKE_CASE_ ( self : int ): pass def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : Optional[Any] , lowercase_ : Any , lowercase_ : List[Any]=None , **lowercase_ : Any ): lowercase_ : Any = VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_ , lowercase_ ) lowercase_ : Dict = TFVisionTextDualEncoderModel(lowercase_ ) lowercase_ : int = model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : str , lowercase_ : List[Any] , lowercase_ : List[Any]=None , **lowercase_ : Tuple ): lowercase_ , lowercase_ : Optional[int] = self.get_vision_text_model(lowercase_ , lowercase_ ) lowercase_ : Union[str, Any] = TFVisionTextDualEncoderModel(vision_model=lowercase_ , text_model=lowercase_ ) lowercase_ : Union[str, Any] = model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : str , lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : List[str]=None , **lowercase_ : List[str] ): lowercase_ , lowercase_ : str = self.get_vision_text_model(lowercase_ , lowercase_ ) lowercase_ : List[str] = {"""vision_model""": vision_model, """text_model""": text_model} lowercase_ : List[str] = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_ ) lowercase_ : Tuple = model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : Dict , lowercase_ : Any , lowercase_ : List[str] , lowercase_ : Any , lowercase_ : Union[str, Any] , lowercase_ : str=None , **lowercase_ : Any ): lowercase_ , lowercase_ : Tuple = self.get_vision_text_model(lowercase_ , lowercase_ ) lowercase_ : Optional[int] = TFVisionTextDualEncoderModel(vision_model=lowercase_ , text_model=lowercase_ ) lowercase_ : int = model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) lowercase_ : str = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase_ ) lowercase_ : List[Any] = TFVisionTextDualEncoderModel.from_pretrained(lowercase_ ) lowercase_ : Dict = model(input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ ) lowercase_ : Optional[int] = after_output[0].numpy() lowercase_ : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase_ , 1E-5 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int , lowercase_ : Any=None , **lowercase_ : Union[str, Any] ): lowercase_ , lowercase_ : List[str] = self.get_vision_text_model(lowercase_ , lowercase_ ) lowercase_ : Any = TFVisionTextDualEncoderModel(vision_model=lowercase_ , text_model=lowercase_ ) lowercase_ : Optional[int] = model( input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ , output_attentions=lowercase_ ) lowercase_ : List[Any] = output.vision_model_output.attentions self.assertEqual(len(lowercase_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase_ : int = to_atuple(vision_model.config.image_size ) lowercase_ : int = to_atuple(vision_model.config.patch_size ) lowercase_ : List[str] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowercase_ : int = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowercase_ : Optional[int] = output.text_model_output.attentions self.assertEqual(len(lowercase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , lowercase_ : np.ndarray , lowercase_ : np.ndarray , lowercase_ : float ): lowercase_ : str = np.abs((a - b) ).max() self.assertLessEqual(lowercase_ , lowercase_ , f'''Difference between torch and flax is {diff} (>= {tol}).''' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): lowercase_ : str = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): lowercase_ : Dict = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): lowercase_ : Dict = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): lowercase_ : Dict = self.prepare_config_and_inputs() self.check_save_load(**lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): lowercase_ : List[Any] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowercase_ ) @slow def SCREAMING_SNAKE_CASE_ ( self : int ): lowercase_ , lowercase_ : Tuple = self.get_pretrained_model_and_inputs() lowercase_ : List[str] = model_a(**lowercase_ ) lowercase_ : Union[str, Any] = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowercase_ ) lowercase_ : str = TFVisionTextDualEncoderModel.from_pretrained(lowercase_ ) lowercase_ : int = model_a(**lowercase_ ) lowercase_ : str = after_outputs[0].numpy() lowercase_ : Dict = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase_ , 1E-5 ) @require_tf class __magic_name__ ( _UpperCAmelCase, unittest.TestCase): def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Tuple = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-random-bert""" ) lowercase_ : Optional[int] = 13 lowercase_ : Tuple = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : List[str] = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowercase_ : Optional[Any] = random_attention_mask([batch_size, 4] ) lowercase_ : Any = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any , lowercase_ : Union[str, Any] ): lowercase_ : Any = TFViTModel(lowercase_ , name="""vision_model""" ) lowercase_ : Optional[Any] = TFBertModel(lowercase_ , name="""text_model""" ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : str ): lowercase_ : Optional[int] = TFViTModelTester(self ) lowercase_ : Tuple = TFBertModelTester(self ) lowercase_ : Optional[int] = vit_model_tester.prepare_config_and_inputs() lowercase_ : Union[str, Any] = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ : Tuple = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Any = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class __magic_name__ ( _UpperCAmelCase, unittest.TestCase): def SCREAMING_SNAKE_CASE_ ( self : str ): # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. lowercase_ : str = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """Rocketknight1/tiny-random-deit-tf""" , """hf-internal-testing/tiny-random-roberta""" ) lowercase_ : Optional[int] = 13 lowercase_ : List[Any] = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : Tuple = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowercase_ : Optional[Any] = random_attention_mask([batch_size, 4] ) lowercase_ : str = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : int , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[Any]=None , **lowercase_ : Union[str, Any] ): lowercase_ , lowercase_ : Any = self.get_vision_text_model(lowercase_ , lowercase_ ) lowercase_ : Dict = TFVisionTextDualEncoderModel(vision_model=lowercase_ , text_model=lowercase_ ) lowercase_ : int = model( input_ids=lowercase_ , pixel_values=lowercase_ , attention_mask=lowercase_ , output_attentions=lowercase_ ) lowercase_ : str = output.vision_model_output.attentions self.assertEqual(len(lowercase_ ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowercase_ : Dict = to_atuple(vision_model.config.image_size ) lowercase_ : Tuple = to_atuple(vision_model.config.patch_size ) lowercase_ : Optional[int] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowercase_ : List[str] = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowercase_ : Dict = output.text_model_output.attentions self.assertEqual(len(lowercase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , lowercase_ : List[str] , lowercase_ : Dict ): lowercase_ : Dict = TFDeiTModel(lowercase_ , name="""vision_model""" ) lowercase_ : Tuple = TFRobertaModel(lowercase_ , name="""text_model""" ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): lowercase_ : Optional[Any] = TFDeiTModelTester(self ) lowercase_ : int = TFRobertaModelTester(self ) lowercase_ : Optional[int] = vit_model_tester.prepare_config_and_inputs() lowercase_ : int = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ : int = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Tuple = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class __magic_name__ ( _UpperCAmelCase, unittest.TestCase): def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): lowercase_ : List[str] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """Rocketknight1/tiny-random-clip-tf""" , """hf-internal-testing/tiny-random-bert""" ) lowercase_ : List[Any] = 13 lowercase_ : Optional[int] = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowercase_ : int = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowercase_ : Any = random_attention_mask([batch_size, 4] ) lowercase_ : Optional[int] = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : Dict , lowercase_ : str , lowercase_ : List[Any] ): lowercase_ : Dict = TFCLIPVisionModel(lowercase_ , name="""vision_model""" ) lowercase_ : Dict = TFBertModel(lowercase_ , name="""text_model""" ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : int ): lowercase_ : Optional[int] = TFCLIPVisionModelTester(self ) lowercase_ : Union[str, Any] = TFBertModelTester(self ) lowercase_ : int = clip_model_tester.prepare_config_and_inputs() lowercase_ : Dict = bert_model_tester.prepare_config_and_inputs() lowercase_ , lowercase_ : int = vision_config_and_inputs ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Tuple = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class __magic_name__ ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Tuple = TFVisionTextDualEncoderModel.from_pretrained( """clip-italian/clip-italian""" , logit_scale_init_value=1.0 , from_pt=lowercase_ ) lowercase_ : Optional[Any] = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) lowercase_ : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowercase_ : Any = processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=lowercase_ , padding=lowercase_ , return_tensors="""np""" ) lowercase_ : Dict = model(**lowercase_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) lowercase_ : List[Any] = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , lowercase_ , atol=1E-3 ) )
21
'''simple docstring''' from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm _lowercase : int = logging.get_logger(__name__) @dataclass class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : Optional[Any] , **lowercase_ : int ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase_ : Optional[int] = deprecated_arg[3:] setattr(self , lowercase_ , not kwargs.pop(lowercase_ ) ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no_{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) lowercase_ : Tuple = kwargs.pop("""torchscript""" , self.torchscript ) lowercase_ : List[Any] = kwargs.pop("""torch_xla_tpu_print_metrics""" , self.torch_xla_tpu_print_metrics ) lowercase_ : List[Any] = kwargs.pop("""fp16_opt_level""" , self.fpaa_opt_level ) super().__init__(**lowercase_ ) UpperCamelCase__ = field(default=_UpperCAmelCase, metadata={'''help''': '''Trace the models using torchscript'''}) UpperCamelCase__ = field(default=_UpperCAmelCase, metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''}) UpperCamelCase__ = field( default='''O1''', metadata={ '''help''': ( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. ''' '''See details at https://nvidia.github.io/apex/amp.html''' ) }, ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : Tuple ): requires_backends(self , ["""torch"""] ) logger.info("""PyTorch: setting up devices""" ) if not self.cuda: lowercase_ : Optional[Any] = torch.device("""cpu""" ) lowercase_ : Tuple = 0 elif is_torch_tpu_available(): lowercase_ : Optional[int] = xm.xla_device() lowercase_ : str = 0 else: lowercase_ : int = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) lowercase_ : str = torch.cuda.device_count() return device, n_gpu @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): return is_torch_tpu_available() and self.tpu @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ): requires_backends(self , ["""torch"""] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): requires_backends(self , ["""torch"""] ) return self._setup_devices[0] @property def SCREAMING_SNAKE_CASE_ ( self : int ): requires_backends(self , ["""torch"""] ) return self._setup_devices[1] @property def SCREAMING_SNAKE_CASE_ ( self : int ): return self.n_gpu > 0
21
1
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowercase__ : Dict = False lowercase__ : Any = logging.get_logger(__name__) lowercase__ : List[Any] = '''ybelkada/fonts''' def __lowercase ( ): if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( f"You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use " '''Pix2StructImageProcessor. Please upgrade torch.''' ) def __lowercase ( _a , _a , _a ): requires_backends(_a , ['''torch'''] ) _check_torch_version() snake_case_ : Optional[int] = image_tensor.unsqueeze(0 ) snake_case_ : List[str] = torch.nn.functional.unfold(_a , (patch_height, patch_width) , stride=(patch_height, patch_width) ) snake_case_ : Union[str, Any] = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , _a , _a , -1 ) snake_case_ : List[Any] = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def __lowercase ( _a , _a = 36 , _a = "black" , _a = "white" , _a = 5 , _a = 5 , _a = 5 , _a = 5 , _a = None , _a = None , ): requires_backends(_a , '''vision''' ) # Add new lines so that each line is no more than 80 characters. snake_case_ : Dict = textwrap.TextWrapper(width=80 ) snake_case_ : List[str] = wrapper.wrap(text=_a ) snake_case_ : Tuple = '\n'.join(_a ) if font_bytes is not None and font_path is None: snake_case_ : Any = io.BytesIO(_a ) elif font_path is not None: snake_case_ : str = font_path else: snake_case_ : Any = hf_hub_download(_a , '''Arial.TTF''' ) snake_case_ : Optional[int] = ImageFont.truetype(_a , encoding='''UTF-8''' , size=_a ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. snake_case_ : int = ImageDraw.Draw(Image.new('''RGB''' , (1, 1) , _a ) ) snake_case_ : Optional[Any] = temp_draw.textbbox((0, 0) , _a , _a ) # Create the actual image with a bit of padding around the text. snake_case_ : Optional[Any] = text_width + left_padding + right_padding snake_case_ : Tuple = text_height + top_padding + bottom_padding snake_case_ : Union[str, Any] = Image.new('''RGB''' , (image_width, image_height) , _a ) snake_case_ : List[Any] = ImageDraw.Draw(_a ) draw.text(xy=(left_padding, top_padding) , text=_a , fill=_a , font=_a ) return image def __lowercase ( _a , _a , **_a ): requires_backends(_a , '''vision''' ) # Convert to PIL image if necessary snake_case_ : Tuple = to_pil_image(_a ) snake_case_ : Union[str, Any] = render_text(_a , **_a ) snake_case_ : List[Any] = max(header_image.width , image.width ) snake_case_ : Any = int(image.height * (new_width / image.width) ) snake_case_ : Union[str, Any] = int(header_image.height * (new_width / header_image.width) ) snake_case_ : List[Any] = Image.new('''RGB''' , (new_width, new_height + new_header_height) , '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary snake_case_ : Optional[Any] = to_numpy_array(_a ) if infer_channel_dimension_format(_a ) == ChannelDimension.LAST: snake_case_ : int = to_channel_dimension_format(_a , ChannelDimension.LAST ) return new_image class _UpperCAmelCase ( snake_case_): _lowerCAmelCase : str = ["""flattened_patches"""] def __init__( self : int , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : int = 2048 , lowercase_ : bool = False , **lowercase_ : str , ): super().__init__(**lowercase_ ) snake_case_ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} snake_case_ : Dict = do_normalize snake_case_ : int = do_convert_rgb snake_case_ : List[str] = max_patches snake_case_ : List[str] = is_vqa def _snake_case ( self : Union[str, Any] , lowercase_ : np.ndarray , lowercase_ : int , lowercase_ : dict , **lowercase_ : Dict ): requires_backends(self.extract_flattened_patches , '''torch''' ) _check_torch_version() # convert to torch snake_case_ : Optional[Any] = to_channel_dimension_format(lowercase_ , ChannelDimension.FIRST ) snake_case_ : str = torch.from_numpy(lowercase_ ) snake_case_ : Optional[Any] = patch_size['height'], patch_size['width'] snake_case_ : List[str] = get_image_size(lowercase_ ) # maximize scale s.t. snake_case_ : Any = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) snake_case_ : Optional[int] = max(min(math.floor(scale * image_height / patch_height ) , lowercase_ ) , 1 ) snake_case_ : str = max(min(math.floor(scale * image_width / patch_width ) , lowercase_ ) , 1 ) snake_case_ : List[Any] = max(num_feasible_rows * patch_height , 1 ) snake_case_ : List[str] = max(num_feasible_cols * patch_width , 1 ) snake_case_ : Any = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='''bilinear''' , align_corners=lowercase_ , antialias=lowercase_ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] snake_case_ : Union[str, Any] = torch_extract_patches(lowercase_ , lowercase_ , lowercase_ ) snake_case_ : str = patches.shape snake_case_ : List[Any] = patches_shape[1] snake_case_ : Union[str, Any] = patches_shape[2] snake_case_ : Optional[Any] = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] snake_case_ : Tuple = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] snake_case_ : Union[str, Any] = torch.arange(lowercase_ ).reshape([rows, 1] ).repeat(1 , lowercase_ ).reshape([rows * columns, 1] ) snake_case_ : List[Any] = torch.arange(lowercase_ ).reshape([1, columns] ).repeat(lowercase_ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] snake_case_ : Any = row_ids.to(torch.floataa ) snake_case_ : Any = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] snake_case_ : Dict = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] snake_case_ : Tuple = torch.nn.functional.pad(lowercase_ , [0, 0, 0, max_patches - (rows * columns)] ).float() snake_case_ : List[Any] = to_numpy_array(lowercase_ ) return result def _snake_case ( self : Any , lowercase_ : np.ndarray , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Dict ): if image.dtype == np.uinta: snake_case_ : int = image.astype(np.floataa ) # take mean across the whole `image` snake_case_ : Optional[Any] = np.mean(lowercase_ ) snake_case_ : List[str] = np.std(lowercase_ ) snake_case_ : Any = max(lowercase_ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , **lowercase_ ) def _snake_case ( self : Optional[int] , lowercase_ : ImageInput , lowercase_ : Optional[str] = None , lowercase_ : bool = None , lowercase_ : Optional[bool] = None , lowercase_ : Optional[int] = None , lowercase_ : Optional[Dict[str, int]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : str , ): snake_case_ : int = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case_ : Any = patch_size if patch_size is not None else self.patch_size snake_case_ : List[Any] = max_patches if max_patches is not None else self.max_patches snake_case_ : Optional[Any] = self.is_vqa if kwargs.get('''data_format''' , lowercase_ ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) snake_case_ : List[str] = 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.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case_ : List[Any] = [convert_to_rgb(lowercase_ ) for image in images] # All transformations expect numpy arrays. snake_case_ : Union[str, Any] = [to_numpy_array(lowercase_ ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) snake_case_ : Optional[int] = kwargs.pop('''font_bytes''' , lowercase_ ) snake_case_ : List[str] = kwargs.pop('''font_path''' , lowercase_ ) if isinstance(lowercase_ , lowercase_ ): snake_case_ : Optional[int] = [header_text] * len(lowercase_ ) snake_case_ : Union[str, Any] = [ render_header(lowercase_ , header_text[i] , font_bytes=lowercase_ , font_path=lowercase_ ) for i, image in enumerate(lowercase_ ) ] if do_normalize: snake_case_ : Optional[int] = [self.normalize(image=lowercase_ ) for image in images] # convert to torch tensor and permute snake_case_ : List[str] = [ self.extract_flattened_patches(image=lowercase_ , max_patches=lowercase_ , patch_size=lowercase_ ) for image in images ] # create attention mask in numpy snake_case_ : int = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] snake_case_ : Optional[Any] = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} , tensor_type=lowercase_ ) return encoded_outputs
264
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int a_ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _lowercase ( datasets.BuilderConfig ): lowercase = None def __lowercase ( lowerCamelCase : "pyspark.sql.DataFrame" , lowerCamelCase : List[int] , ): import pyspark def generate_fn(): UpperCamelCase_ : Dict = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: UpperCamelCase_ : Tuple = df_with_partition_id.select('*' ).where(F"part_id = {partition_id}" ).drop('part_id' ) UpperCamelCase_ : Union[str, Any] = partition_df.collect() UpperCamelCase_ : Any = 0 for row in rows: yield F"{partition_id}_{row_id}", row.asDict() row_id += 1 return generate_fn class _lowercase ( _BaseExamplesIterable ): def __init__( self : Optional[int] , snake_case : "pyspark.sql.DataFrame" , snake_case : Tuple=None , ) -> Tuple: """simple docstring""" UpperCamelCase_ : Dict = df UpperCamelCase_ : int = partition_order or range(self.df.rdd.getNumPartitions() ) UpperCamelCase_ : Optional[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Optional[int] ) -> Any: """simple docstring""" yield from self.generate_examples_fn() def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : np.random.Generator ) -> "SparkExamplesIterable": """simple docstring""" UpperCamelCase_ : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(snake_case ) return SparkExamplesIterable(self.df , partition_order=snake_case ) def SCREAMING_SNAKE_CASE__ ( self : int , snake_case : int , snake_case : int ) -> "SparkExamplesIterable": """simple docstring""" UpperCamelCase_ : Tuple = self.split_shard_indices_by_worker(snake_case , snake_case ) return SparkExamplesIterable(self.df , partition_order=snake_case ) @property def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: """simple docstring""" return len(self.partition_order ) class _lowercase ( datasets.DatasetBuilder ): lowercase = SparkConfig def __init__( self : List[Any] , snake_case : "pyspark.sql.DataFrame" , snake_case : str = None , snake_case : str = None , **snake_case : Optional[Any] , ) -> List[str]: """simple docstring""" import pyspark UpperCamelCase_ : List[Any] = pyspark.sql.SparkSession.builder.getOrCreate() UpperCamelCase_ : str = df UpperCamelCase_ : Tuple = working_dir super().__init__( cache_dir=snake_case , config_name=str(self.df.semanticHash() ) , **snake_case , ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Dict: """simple docstring""" def create_cache_and_write_probe(snake_case : str ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=snake_case ) UpperCamelCase_ : Tuple = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(snake_case , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: UpperCamelCase_ : Tuple = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(snake_case ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Union[str, Any]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : datasets.download.download_manager.DownloadManager ) -> Optional[int]: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : Optional[int] ) -> List[Any]: """simple docstring""" import pyspark def get_arrow_batch_size(snake_case : Dict ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) UpperCamelCase_ : List[str] = self.df.count() UpperCamelCase_ : Union[str, Any] = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. UpperCamelCase_ : str = ( self.df.limit(snake_case ) .repartition(1 ) .mapInArrow(snake_case , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) UpperCamelCase_ : Optional[int] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. UpperCamelCase_ : Optional[Any] = min(snake_case , int(approx_total_size / max_shard_size ) ) UpperCamelCase_ : int = self.df.repartition(snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : str , snake_case : str , snake_case : int , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: """simple docstring""" import pyspark UpperCamelCase_ : List[Any] = ParquetWriter if file_format == 'parquet' else ArrowWriter UpperCamelCase_ : List[str] = os.path.join(self._working_dir , os.path.basename(snake_case ) ) if self._working_dir else fpath UpperCamelCase_ : Union[str, Any] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. UpperCamelCase_ : Union[str, Any] = self.config.features UpperCamelCase_ : Any = self._writer_batch_size UpperCamelCase_ : Dict = self._fs.storage_options def write_arrow(snake_case : List[str] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. UpperCamelCase_ : Any = pyspark.TaskContext().taskAttemptId() UpperCamelCase_ : str = next(snake_case , snake_case ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) UpperCamelCase_ : Any = 0 UpperCamelCase_ : Optional[Any] = writer_class( features=snake_case , path=working_fpath.replace('SSSSS' , f"{shard_id:05d}" ).replace('TTTTT' , f"{task_id:05d}" ) , writer_batch_size=snake_case , storage_options=snake_case , embed_local_files=snake_case , ) UpperCamelCase_ : str = pa.Table.from_batches([first_batch] ) writer.write_table(snake_case ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: UpperCamelCase_, UpperCamelCase_ : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 UpperCamelCase_ : Union[str, Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f"{shard_id:05d}" ).replace('TTTTT' , f"{task_id:05d}" ) , writer_batch_size=snake_case , storage_options=snake_case , embed_local_files=snake_case , ) UpperCamelCase_ : Optional[Any] = pa.Table.from_batches([batch] ) writer.write_table(snake_case ) if writer._num_bytes > 0: UpperCamelCase_, UpperCamelCase_ : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(snake_case ) ): UpperCamelCase_ : Dict = os.path.join(os.path.dirname(snake_case ) , os.path.basename(snake_case ) ) shutil.move(snake_case , snake_case ) UpperCamelCase_ : int = ( self.df.mapInArrow(snake_case , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def SCREAMING_SNAKE_CASE__ ( self : int , snake_case : "datasets.SplitGenerator" , snake_case : str = "arrow" , snake_case : Optional[Union[str, int]] = None , snake_case : Optional[int] = None , **snake_case : Any , ) -> int: """simple docstring""" self._validate_cache_dir() UpperCamelCase_ : Optional[int] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(snake_case ) UpperCamelCase_ : List[str] = not is_remote_filesystem(self._fs ) UpperCamelCase_ : List[Any] = os.path.join if is_local else posixpath.join UpperCamelCase_ : Optional[int] = '-TTTTT-SSSSS-of-NNNNN' UpperCamelCase_ : Dict = f"{self.name}-{split_generator.name}{SUFFIX}.{file_format}" UpperCamelCase_ : int = path_join(self._output_dir , snake_case ) UpperCamelCase_ : int = 0 UpperCamelCase_ : Optional[int] = 0 UpperCamelCase_ : Union[str, Any] = 0 UpperCamelCase_ : Optional[Any] = [] UpperCamelCase_ : Any = [] for task_id, content in self._prepare_split_single(snake_case , snake_case , snake_case ): ( ( UpperCamelCase_ ), ( UpperCamelCase_ ), ( UpperCamelCase_ ), ( UpperCamelCase_ ), ) : Optional[Any] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(snake_case ) UpperCamelCase_ : Optional[Any] = total_num_examples UpperCamelCase_ : Any = total_num_bytes # should rename everything at the end logger.debug(f"Renaming {total_shards} shards." ) if total_shards > 1: UpperCamelCase_ : List[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. UpperCamelCase_ : int = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( snake_case : int , snake_case : int , snake_case : int , ): rename( snake_case , fpath.replace('SSSSS' , f"{shard_id:05d}" ).replace('TTTTT' , f"{task_id:05d}" ) , fpath.replace('TTTTT-SSSSS' , f"{global_shard_id:05d}" ).replace('NNNNN' , f"{total_shards:05d}" ) , ) UpperCamelCase_ : Any = [] UpperCamelCase_ : Optional[int] = 0 for i in range(len(snake_case ) ): UpperCamelCase_, UpperCamelCase_ : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(snake_case ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(snake_case , len(snake_case ) ).map(lambda snake_case : _rename_shard(*snake_case ) ).collect() else: # don't use any pattern UpperCamelCase_ : Tuple = 0 UpperCamelCase_ : Optional[Any] = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f"{shard_id:05d}" ).replace('TTTTT' , f"{task_id:05d}" ) , fpath.replace(snake_case , '' ) , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : "datasets.SplitGenerator" , ) -> SparkExamplesIterable: """simple docstring""" return SparkExamplesIterable(self.df )
175
0
'''simple docstring''' from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( """The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ , UpperCamelCase__ , ) class __A ( UpperCamelCase__ ): a__ : int = RobertaConfig a__ : Optional[Any] = """roberta""" def __init__(self : Dict , __a : str ): super().__init__(__a ) UpperCAmelCase_ = RobertaEmbeddings(__a ) self.init_weights() @add_start_docstrings( """RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. """ , UpperCamelCase__ , ) class __A ( UpperCamelCase__ ): a__ : str = RobertaConfig a__ : Optional[int] = """roberta""" def __init__(self : List[Any] , __a : str ): super().__init__(__a ) UpperCAmelCase_ = config.num_labels UpperCAmelCase_ = config.num_hidden_layers UpperCAmelCase_ = DeeRobertaModel(__a ) UpperCAmelCase_ = nn.Dropout(config.hidden_dropout_prob ) UpperCAmelCase_ = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(__a ) def _lowercase (self : Optional[int] , __a : int=None , __a : List[str]=None , __a : List[str]=None , __a : List[str]=None , __a : List[str]=None , __a : List[str]=None , __a : Union[str, Any]=None , __a : Optional[Any]=-1 , __a : List[str]=False , ): UpperCAmelCase_ = self.num_layers try: UpperCAmelCase_ = self.roberta( __a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , ) UpperCAmelCase_ = outputs[1] UpperCAmelCase_ = self.dropout(__a ) UpperCAmelCase_ = self.classifier(__a ) UpperCAmelCase_ = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: UpperCAmelCase_ = e.message UpperCAmelCase_ = e.exit_layer UpperCAmelCase_ = outputs[0] if not self.training: UpperCAmelCase_ = entropy(__a ) UpperCAmelCase_ = [] UpperCAmelCase_ = [] if labels is not None: if self.num_labels == 1: # We are doing regression UpperCAmelCase_ = MSELoss() UpperCAmelCase_ = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: UpperCAmelCase_ = CrossEntropyLoss() UpperCAmelCase_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits UpperCAmelCase_ = [] for highway_exit in outputs[-1]: UpperCAmelCase_ = highway_exit[0] if not self.training: highway_logits_all.append(__a ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression UpperCAmelCase_ = MSELoss() UpperCAmelCase_ = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: UpperCAmelCase_ = CrossEntropyLoss() UpperCAmelCase_ = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__a ) if train_highway: UpperCAmelCase_ = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: UpperCAmelCase_ = (loss,) + outputs if not self.training: UpperCAmelCase_ = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: UpperCAmelCase_ = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
106
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('1.0.0a'): raise Exception('requires fairseq >= 1.0.0a') logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: List[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ='Hello world! cécé herlolip' def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str , snake_case_ : bool ) -> Any: '''simple docstring''' UpperCAmelCase_ = FairseqRobertaModel.from_pretrained(snake_case_ ) roberta.eval() # disable dropout UpperCAmelCase_ = roberta.model.encoder.sentence_encoder UpperCAmelCase_ = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: UpperCAmelCase_ = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , snake_case_ ) UpperCAmelCase_ = XLMRobertaXLForSequenceClassification(snake_case_ ) if classification_head else XLMRobertaXLForMaskedLM(snake_case_ ) model.eval() # Now let's copy all the weights. # Embeddings UpperCAmelCase_ = roberta_sent_encoder.embed_tokens.weight UpperCAmelCase_ = roberta_sent_encoder.embed_positions.weight UpperCAmelCase_ = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. UpperCAmelCase_ = roberta_sent_encoder.layer_norm.weight UpperCAmelCase_ = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer UpperCAmelCase_ = model.roberta.encoder.layer[i] UpperCAmelCase_ = roberta_sent_encoder.layers[i] UpperCAmelCase_ = layer.attention UpperCAmelCase_ = roberta_layer.self_attn_layer_norm.weight UpperCAmelCase_ = roberta_layer.self_attn_layer_norm.bias # self attention UpperCAmelCase_ = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) UpperCAmelCase_ = roberta_layer.self_attn.q_proj.weight UpperCAmelCase_ = roberta_layer.self_attn.q_proj.bias UpperCAmelCase_ = roberta_layer.self_attn.k_proj.weight UpperCAmelCase_ = roberta_layer.self_attn.k_proj.bias UpperCAmelCase_ = roberta_layer.self_attn.v_proj.weight UpperCAmelCase_ = roberta_layer.self_attn.v_proj.bias # self-attention output UpperCAmelCase_ = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape UpperCAmelCase_ = roberta_layer.self_attn.out_proj.weight UpperCAmelCase_ = roberta_layer.self_attn.out_proj.bias # this one is final layer norm UpperCAmelCase_ = roberta_layer.final_layer_norm.weight UpperCAmelCase_ = roberta_layer.final_layer_norm.bias # intermediate UpperCAmelCase_ = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape UpperCAmelCase_ = roberta_layer.fca.weight UpperCAmelCase_ = roberta_layer.fca.bias # output UpperCAmelCase_ = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape UpperCAmelCase_ = roberta_layer.fca.weight UpperCAmelCase_ = roberta_layer.fca.bias # end of layer if classification_head: UpperCAmelCase_ = roberta.model.classification_heads["mnli"].dense.weight UpperCAmelCase_ = roberta.model.classification_heads["mnli"].dense.bias UpperCAmelCase_ = roberta.model.classification_heads["mnli"].out_proj.weight UpperCAmelCase_ = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head UpperCAmelCase_ = roberta.model.encoder.lm_head.dense.weight UpperCAmelCase_ = roberta.model.encoder.lm_head.dense.bias UpperCAmelCase_ = roberta.model.encoder.lm_head.layer_norm.weight UpperCAmelCase_ = roberta.model.encoder.lm_head.layer_norm.bias UpperCAmelCase_ = roberta.model.encoder.lm_head.weight UpperCAmelCase_ = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. UpperCAmelCase_ = roberta.encode(snake_case_ ).unsqueeze(0 ) # batch of size 1 UpperCAmelCase_ = model(snake_case_ )[0] if classification_head: UpperCAmelCase_ = roberta.model.classification_heads["mnli"](roberta.extract_features(snake_case_ ) ) else: UpperCAmelCase_ = roberta.model(snake_case_ )[0] print(our_output.shape , their_output.shape ) UpperCAmelCase_ = torch.max(torch.abs(our_output - their_output ) ).item() print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 UpperCAmelCase_ = torch.allclose(snake_case_ , snake_case_ , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(snake_case_ ).mkdir(parents=snake_case_ , exist_ok=snake_case_ ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
106
1
a : Tuple = frozenset( [ "prompt", "height", "width", "guidance_scale", "negative_prompt", "prompt_embeds", "negative_prompt_embeds", "cross_attention_kwargs", ] ) a : str = frozenset(["prompt", "negative_prompt"]) a : List[Any] = frozenset([]) a : List[Any] = frozenset(["image"]) a : Any = frozenset( [ "image", "height", "width", "guidance_scale", ] ) a : List[str] = frozenset(["image"]) a : int = frozenset( [ "prompt", "image", "height", "width", "guidance_scale", "negative_prompt", "prompt_embeds", "negative_prompt_embeds", ] ) a : Dict = frozenset(["prompt", "image", "negative_prompt"]) a : Optional[int] = frozenset( [ # Text guided image variation with an image mask "prompt", "image", "mask_image", "height", "width", "guidance_scale", "negative_prompt", "prompt_embeds", "negative_prompt_embeds", ] ) a : Optional[int] = frozenset(["prompt", "image", "mask_image", "negative_prompt"]) a : Optional[int] = frozenset( [ # image variation with an image mask "image", "mask_image", "height", "width", "guidance_scale", ] ) a : Union[str, Any] = frozenset(["image", "mask_image"]) a : Optional[int] = frozenset( [ "example_image", "image", "mask_image", "height", "width", "guidance_scale", ] ) a : Tuple = frozenset(["example_image", "image", "mask_image"]) a : Optional[int] = frozenset(["class_labels"]) a : List[Any] = frozenset(["class_labels"]) a : str = frozenset(["batch_size"]) a : Any = frozenset([]) a : List[Any] = frozenset(["batch_size"]) a : Union[str, Any] = frozenset([]) a : Dict = frozenset( [ "prompt", "audio_length_in_s", "guidance_scale", "negative_prompt", "prompt_embeds", "negative_prompt_embeds", "cross_attention_kwargs", ] ) a : Union[str, Any] = frozenset(["prompt", "negative_prompt"]) a : Tuple = frozenset(["input_tokens"]) a : List[Any] = frozenset(["input_tokens"])
114
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = 384 SCREAMING_SNAKE_CASE__ : Tuple = 7 if "tiny" in model_name: SCREAMING_SNAKE_CASE__ : int = 96 SCREAMING_SNAKE_CASE__ : str = (2, 2, 6, 2) SCREAMING_SNAKE_CASE__ : List[Any] = (3, 6, 12, 24) elif "small" in model_name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 96 SCREAMING_SNAKE_CASE__ : Any = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : Tuple = (3, 6, 12, 24) elif "base" in model_name: SCREAMING_SNAKE_CASE__ : Tuple = 128 SCREAMING_SNAKE_CASE__ : List[Any] = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : int = (4, 8, 16, 32) SCREAMING_SNAKE_CASE__ : Optional[int] = 12 SCREAMING_SNAKE_CASE__ : Optional[int] = 512 elif "large" in model_name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 192 SCREAMING_SNAKE_CASE__ : int = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : int = (6, 12, 24, 48) SCREAMING_SNAKE_CASE__ : List[Any] = 12 SCREAMING_SNAKE_CASE__ : Optional[Any] = 768 # set label information SCREAMING_SNAKE_CASE__ : Optional[Any] = 150 SCREAMING_SNAKE_CASE__ : Tuple = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ : List[str] = """ade20k-id2label.json""" SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(_snake_case ,_snake_case ,repo_type="""dataset""" ) ,"""r""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(_snake_case ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[Any] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = SwinConfig( embed_dim=_snake_case ,depths=_snake_case ,num_heads=_snake_case ,window_size=_snake_case ,out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ,) SCREAMING_SNAKE_CASE__ : int = UperNetConfig( backbone_config=_snake_case ,auxiliary_in_channels=_snake_case ,num_labels=_snake_case ,idalabel=_snake_case ,labelaid=_snake_case ,) return config def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [] # fmt: off # stem rename_keys.append(("""backbone.patch_embed.projection.weight""", """backbone.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.projection.bias""", """backbone.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """backbone.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """backbone.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.stages.{i}.downsample.reduction.weight''', f'''backbone.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.weight''', f'''backbone.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.bias''', f'''backbone.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = dct.pop(_snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = val def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : int = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_bias[-dim :] # fmt: on def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = x.shape SCREAMING_SNAKE_CASE__ : List[Any] = x.reshape(_snake_case ,4 ,in_channel // 4 ) SCREAMING_SNAKE_CASE__ : Dict = x[:, [0, 2, 1, 3], :].transpose(1 ,2 ).reshape(_snake_case ,_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = x.shape SCREAMING_SNAKE_CASE__ : Any = x.reshape(_snake_case ,in_channel // 4 ,4 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = x[:, :, [0, 2, 1, 3]].transpose(1 ,2 ).reshape(_snake_case ,_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Tuple = x.shape[0] SCREAMING_SNAKE_CASE__ : List[str] = x.reshape(4 ,in_channel // 4 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = x[[0, 2, 1, 3], :].transpose(0 ,1 ).reshape(_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : int = x.shape[0] SCREAMING_SNAKE_CASE__ : List[str] = x.reshape(in_channel // 4 ,4 ) SCREAMING_SNAKE_CASE__ : Tuple = x[:, [0, 2, 1, 3]].transpose(0 ,1 ).reshape(_snake_case ) return x def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = { """upernet-swin-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth""", """upernet-swin-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth""", """upernet-swin-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth""", """upernet-swin-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth""", } SCREAMING_SNAKE_CASE__ : Optional[int] = model_name_to_url[model_name] SCREAMING_SNAKE_CASE__ : Optional[int] = torch.hub.load_state_dict_from_url(_snake_case ,map_location="""cpu""" ,file_name=_snake_case )[ """state_dict""" ] for name, param in state_dict.items(): print(_snake_case ,param.shape ) SCREAMING_SNAKE_CASE__ : Optional[Any] = get_upernet_config(_snake_case ) SCREAMING_SNAKE_CASE__ : List[str] = UperNetForSemanticSegmentation(_snake_case ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(_snake_case ) if "bn" in key: SCREAMING_SNAKE_CASE__ : Optional[int] = key.replace("""bn""" ,"""batch_norm""" ) SCREAMING_SNAKE_CASE__ : Dict = val # rename keys SCREAMING_SNAKE_CASE__ : str = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case ,_snake_case ,_snake_case ) read_in_q_k_v(_snake_case ,config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] = reverse_correct_unfold_reduction_order(_snake_case ) if "norm" in key: SCREAMING_SNAKE_CASE__ : Tuple = reverse_correct_unfold_norm_order(_snake_case ) model.load_state_dict(_snake_case ) # verify on image SCREAMING_SNAKE_CASE__ : List[str] = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(_snake_case ,stream=_snake_case ).raw ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SegformerImageProcessor() SCREAMING_SNAKE_CASE__ : Optional[int] = processor(_snake_case ,return_tensors="""pt""" ).pixel_values with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Tuple = model(_snake_case ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits print(logits.shape ) print("""First values of logits:""" ,logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ) elif model_name == "upernet-swin-small": SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor( [[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]] ) elif model_name == "upernet-swin-base": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]] ) elif model_name == "upernet-swin-large": SCREAMING_SNAKE_CASE__ : Dict = torch.tensor( [[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]] ) print("""Logits:""" ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,_snake_case ,atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_snake_case ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": UpperCAmelCase__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-swin-tiny', type=str, choices=[f"""upernet-swin-{size}""" for size in ['tiny', 'small', 'base', 'large']], help='Name of the Swin + UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) UpperCAmelCase__ : List[str] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
25
0
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A = logging.get_logger(__name__) class lowercase_ ( _a ): UpperCamelCase_ : Any = ["""pixel_values"""] def __init__( self : List[str] , A__ : str = True , A__ : List[Any] = None , A__ : Any = PILImageResampling.BICUBIC , A__ : int = True , A__ : int = None , A__ : Optional[int] = True , A__ : List[str] = 1 / 255 , A__ : Any = True , A__ : Any = IMAGENET_DEFAULT_MEAN , A__ : Any = IMAGENET_DEFAULT_STD , **A__ : str , ) -> None: super().__init__(**A__ ) _snake_case = size if size is not None else {'shortest_edge': 224} _snake_case = get_size_dict(A__ , default_to_square=A__ ) _snake_case = crop_size if crop_size is not None else {'height': 224, 'width': 224} _snake_case = get_size_dict(A__ , param_name='''crop_size''' ) _snake_case = do_resize _snake_case = size _snake_case = resample _snake_case = do_center_crop _snake_case = crop_size _snake_case = do_rescale _snake_case = rescale_factor _snake_case = do_normalize _snake_case = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _snake_case = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Optional[Any] , A__ : Dict , A__ : Union[str, Any] , A__ : str = PILImageResampling.BICUBIC , A__ : str = None , **A__ : Union[str, Any] , ) -> np.ndarray: _snake_case = get_size_dict(A__ , default_to_square=A__ ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: _snake_case = int((256 / 224) * size['''shortest_edge'''] ) _snake_case = get_resize_output_image_size(A__ , size=A__ , default_to_square=A__ ) _snake_case = {'height': output_size[0], 'width': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f"""Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}""" ) return resize( A__ , size=(size_dict['''height'''], size_dict['''width''']) , resample=A__ , data_format=A__ , **A__ ) def UpperCamelCase_ ( self : Tuple , A__ : Union[str, Any] , A__ : Optional[int] , A__ : Optional[Any] = None , **A__ : int , ) -> np.ndarray: _snake_case = get_size_dict(A__ ) if "height" not in size or "width" not in size: raise ValueError(f"""Size dict must have keys \'height\' and \'width\'. Got {size.keys()}""" ) return center_crop(A__ , size=(size['''height'''], size['''width''']) , data_format=A__ , **A__ ) def UpperCamelCase_ ( self : Tuple , A__ : str , A__ : str , A__ : str = None , **A__ : Any , ) -> np.ndarray: return rescale(A__ , scale=A__ , data_format=A__ , **A__ ) def UpperCamelCase_ ( self : Optional[int] , A__ : Union[str, Any] , A__ : Tuple , A__ : List[Any] , A__ : List[str] = None , **A__ : Tuple , ) -> np.ndarray: return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ ) def UpperCamelCase_ ( self : Any , A__ : int , A__ : Tuple = None , A__ : str = None , A__ : Optional[Any] = None , A__ : int = None , A__ : Dict = None , A__ : int = None , A__ : str = None , A__ : Dict = None , A__ : Dict = None , A__ : List[str] = None , A__ : int = None , A__ : Tuple = ChannelDimension.FIRST , **A__ : Optional[int] , ) -> BatchFeature: _snake_case = do_resize if do_resize is not None else self.do_resize _snake_case = resample if resample is not None else self.resample _snake_case = do_center_crop if do_center_crop is not None else self.do_center_crop _snake_case = do_rescale if do_rescale is not None else self.do_rescale _snake_case = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case = do_normalize if do_normalize is not None else self.do_normalize _snake_case = image_mean if image_mean is not None else self.image_mean _snake_case = image_std if image_std is not None else self.image_std _snake_case = size if size is not None else self.size _snake_case = get_size_dict(A__ , default_to_square=A__ ) _snake_case = crop_size if crop_size is not None else self.crop_size _snake_case = get_size_dict(A__ , param_name='''crop_size''' ) _snake_case = make_list_of_images(A__ ) if not valid_images(A__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _snake_case = [to_numpy_array(A__ ) for image in images] if do_resize: _snake_case = [self.resize(A__ , A__ , A__ ) for image in images] if do_center_crop: _snake_case = [self.center_crop(A__ , A__ ) for image in images] if do_rescale: _snake_case = [self.rescale(A__ , A__ ) for image in images] if do_normalize: _snake_case = [self.normalize(A__ , A__ , A__ ) for image in images] _snake_case = [to_channel_dimension_format(A__ , A__ ) for image in images] _snake_case = {'pixel_values': images} return BatchFeature(data=A__ , tensor_type=A__ )
368
def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) _snake_case = str(bin(_UpperCamelCase ) )[2:] # remove the leading "0b" _snake_case = str(bin(_UpperCamelCase ) )[2:] _snake_case = max(len(_UpperCamelCase ) , len(_UpperCamelCase ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(_UpperCamelCase ) , b_binary.zfill(_UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
278
0
import math def __UpperCamelCase ( lowerCAmelCase__ : int ): return math.sqrt(lowerCAmelCase__ ) * math.sqrt(lowerCAmelCase__ ) == num def __UpperCamelCase ( lowerCAmelCase__ : int ): __a : Optional[int] = 0 __a : int = n while left <= right: __a : Any = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: __a : int = mid - 1 else: __a : List[Any] = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
216
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def __UpperCamelCase ( lowerCAmelCase__ : Any ): # vision encoder if "img_encoder.pos_embed" in name: __a : Any = name.replace('''img_encoder.pos_embed''' , '''vision_model.embeddings.position_embeddings''' ) if "img_encoder.patch_embed.proj" in name: __a : str = name.replace('''img_encoder.patch_embed.proj''' , '''vision_model.embeddings.patch_embeddings.projection''' ) if "img_encoder.patch_embed.norm" in name: __a : int = name.replace('''img_encoder.patch_embed.norm''' , '''vision_model.embeddings.layernorm''' ) if "img_encoder.layers" in name: __a : Union[str, Any] = name.replace('''img_encoder.layers''' , '''vision_model.encoder.stages''' ) if "blocks" in name and "res" not in name: __a : List[Any] = name.replace('''blocks''' , '''layers''' ) if "attn" in name and "pre_assign" not in name: __a : Tuple = name.replace('''attn''' , '''self_attn''' ) if "proj" in name and "self_attn" in name and "text" not in name: __a : List[Any] = name.replace('''proj''' , '''out_proj''' ) if "pre_assign_attn.attn.proj" in name: __a : Any = name.replace('''pre_assign_attn.attn.proj''' , '''pre_assign_attn.attn.out_proj''' ) if "norm1" in name: __a : Union[str, Any] = name.replace('''norm1''' , '''layer_norm1''' ) if "norm2" in name and "pre_assign" not in name: __a : Optional[int] = name.replace('''norm2''' , '''layer_norm2''' ) if "img_encoder.norm" in name: __a : Union[str, Any] = name.replace('''img_encoder.norm''' , '''vision_model.layernorm''' ) # text encoder if "text_encoder.token_embedding" in name: __a : List[Any] = name.replace('''text_encoder.token_embedding''' , '''text_model.embeddings.token_embedding''' ) if "text_encoder.positional_embedding" in name: __a : Any = name.replace('''text_encoder.positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "text_encoder.transformer.resblocks." in name: __a : Any = name.replace('''text_encoder.transformer.resblocks.''' , '''text_model.encoder.layers.''' ) if "ln_1" in name: __a : str = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __a : Union[str, Any] = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __a : Union[str, Any] = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __a : Union[str, Any] = name.replace('''c_proj''' , '''fc2''' ) if "text_encoder" in name: __a : Optional[int] = name.replace('''text_encoder''' , '''text_model''' ) if "ln_final" in name: __a : str = name.replace('''ln_final''' , '''final_layer_norm''' ) # projection layers if "img_projector.linear_hidden." in name: __a : List[str] = name.replace('''img_projector.linear_hidden.''' , '''visual_projection.''' ) if "img_projector.linear_out." in name: __a : str = name.replace('''img_projector.linear_out.''' , '''visual_projection.3.''' ) if "text_projector.linear_hidden" in name: __a : int = name.replace('''text_projector.linear_hidden''' , '''text_projection''' ) if "text_projector.linear_out" in name: __a : List[str] = name.replace('''text_projector.linear_out''' , '''text_projection.3''' ) return name def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Tuple ): for key in orig_state_dict.copy().keys(): __a : List[Any] = orig_state_dict.pop(lowerCAmelCase__ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a : Tuple = key.split('''.''' ) __a , __a : List[Any] = int(key_split[2] ), int(key_split[4] ) __a : List[Any] = config.vision_config.hidden_size if "weight" in key: __a : int = val[:dim, :] __a : List[str] = val[dim : dim * 2, :] __a : List[Any] = val[-dim:, :] else: __a : List[str] = val[:dim] __a : int = val[dim : dim * 2] __a : Any = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a : int = key.split('''.''' ) __a : str = int(key_split[3] ) __a : List[Any] = config.text_config.hidden_size if "weight" in key: __a : List[str] = val[:dim, :] __a : Any = val[ dim : dim * 2, : ] __a : Dict = val[-dim:, :] else: __a : List[str] = val[:dim] __a : Any = val[dim : dim * 2] __a : Any = val[-dim:] else: __a : Union[str, Any] = rename_key(lowerCAmelCase__ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): __a : List[Any] = val.squeeze_() else: __a : Dict = val return orig_state_dict def __UpperCamelCase ( ): __a : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __a : str = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def __UpperCamelCase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any]="groupvit-gcc-yfcc" , lowerCAmelCase__ : int=False ): __a : Union[str, Any] = GroupViTConfig() __a : int = GroupViTModel(lowerCAmelCase__ ).eval() __a : Any = torch.load(lowerCAmelCase__ , map_location='''cpu''' )['''model'''] __a : Optional[Any] = convert_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) __a , __a : Dict = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowerCAmelCase__ ) == 0) # verify result __a : Any = CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) __a : Optional[Any] = prepare_img() __a : Optional[int] = processor(text=['''a photo of a cat''', '''a photo of a dog'''] , images=lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors='''pt''' ) with torch.no_grad(): __a : Tuple = model(**lowerCAmelCase__ ) if model_name == "groupvit-gcc-yfcc": __a : List[str] = torch.tensor([[13.35_23, 6.36_29]] ) elif model_name == "groupvit-gcc-redcaps": __a : List[str] = torch.tensor([[16.18_73, 8.62_30]] ) else: raise ValueError(f"Model name {model_name} not supported." ) assert torch.allclose(outputs.logits_per_image , lowerCAmelCase__ , atol=1e-3 ) processor.save_pretrained(lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) print('''Successfully saved processor and model to''' , lowerCAmelCase__ ) if push_to_hub: print('''Pushing to the hub...''' ) processor.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) model.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) if __name__ == "__main__": lowercase__ =argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.' ) parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint') parser.add_argument( '--model_name', default='groupvit-gccy-fcc', type=str, help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.', ) lowercase__ =parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
216
1
import numpy as np def UpperCAmelCase_ ( __UpperCAmelCase : np.ndarray , __UpperCAmelCase : np.ndarray , __UpperCAmelCase : float = 1E-12 , __UpperCAmelCase : int = 1_00 , ) -> tuple[float, np.ndarray]: assert np.shape(__UpperCAmelCase )[0] == np.shape(__UpperCAmelCase )[1] # Ensure proper dimensionality. assert np.shape(__UpperCAmelCase )[0] == np.shape(__UpperCAmelCase )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(__UpperCAmelCase ) == np.iscomplexobj(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = np.iscomplexobj(__UpperCAmelCase ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(__UpperCAmelCase , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1E12 while not convergence: # Multiple matrix by the vector. SCREAMING_SNAKE_CASE_ = np.dot(__UpperCAmelCase , __UpperCAmelCase ) # Normalize the resulting output vector. SCREAMING_SNAKE_CASE_ = w / np.linalg.norm(__UpperCAmelCase ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) SCREAMING_SNAKE_CASE_ = vector.conj().T if is_complex else vector.T SCREAMING_SNAKE_CASE_ = np.dot(__UpperCAmelCase , np.dot(__UpperCAmelCase , __UpperCAmelCase ) ) # Check convergence. SCREAMING_SNAKE_CASE_ = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = lambda_ if is_complex: SCREAMING_SNAKE_CASE_ = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase_ ( ) -> None: SCREAMING_SNAKE_CASE_ = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) SCREAMING_SNAKE_CASE_ = np.array([41, 4, 20] ) SCREAMING_SNAKE_CASE_ = real_input_matrix.astype(np.complexaaa ) SCREAMING_SNAKE_CASE_ = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T SCREAMING_SNAKE_CASE_ = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": SCREAMING_SNAKE_CASE_ = real_input_matrix SCREAMING_SNAKE_CASE_ = real_vector elif problem_type == "complex": SCREAMING_SNAKE_CASE_ = complex_input_matrix SCREAMING_SNAKE_CASE_ = complex_vector # Our implementation. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = power_iteration(__UpperCAmelCase , __UpperCAmelCase ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = np.linalg.eigh(__UpperCAmelCase ) # Last eigenvalue is the maximum one. SCREAMING_SNAKE_CASE_ = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. SCREAMING_SNAKE_CASE_ = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(__UpperCAmelCase ) - np.abs(__UpperCAmelCase ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
210
def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : int ) -> int: return int((input_a, input_a).count(0 ) != 0 ) def UpperCAmelCase_ ( ) -> None: assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
210
1
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
from graphs.minimum_spanning_tree_kruskal import kruskal def __magic_name__ ( ) -> Union[str, Any]: __lowerCamelCase = 9 __lowerCamelCase = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __lowerCamelCase = kruskal(_lowerCamelCase , _lowerCamelCase ) __lowerCamelCase = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(_lowerCamelCase ) == sorted(_lowerCamelCase )
370
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
339
0