code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from 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 : Optional[Any] =logging.get_logger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Any = [ "no_inference", "no_cuda", "no_tpu", "no_speed", "no_memory", "no_env_print", "no_multi_process", ] def __init__( self : List[str] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A : str =deprecated_arg[3:] setattr(self , SCREAMING_SNAKE_CASE__ , not kwargs.pop(SCREAMING_SNAKE_CASE__ ) ) logger.warning( f'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' f' {positive_arg}={kwargs[positive_arg]}' ) A : Dict =kwargs.pop('torchscript' , self.torchscript ) A : List[str] =kwargs.pop('torch_xla_tpu_print_metrics' , self.torch_xla_tpu_print_metrics ) A : Union[str, Any] =kwargs.pop('fp16_opt_level' , self.fpaa_opt_level ) super().__init__(**SCREAMING_SNAKE_CASE__ ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace the models using torchscript"} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Print Xla/PyTorch tpu metrics"} ) lowercase : str = 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 : Union[str, Any] ) -> Tuple["torch.device", int]: requires_backends(self , ['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: A : List[str] =torch.device('cpu' ) A : Union[str, Any] =0 elif is_torch_tpu_available(): A : Union[str, Any] =xm.xla_device() A : Union[str, Any] =0 else: A : List[str] =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) A : Tuple =torch.cuda.device_count() return device, n_gpu @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: return is_torch_tpu_available() and self.tpu @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> int: requires_backends(self , ['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> "torch.device": requires_backends(self , ['torch'] ) return self._setup_devices[0] @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: requires_backends(self , ['torch'] ) return self._setup_devices[1] @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: return self.n_gpu > 0
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
def A__ ( lowercase: str, lowercase: str ) -> Optional[int]: assert x is not None assert y is not None A : str =len(lowercase ) A : Dict =len(lowercase ) # declaring the array for storing the dp values A : List[Any] =[[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1, m + 1 ): for j in range(1, n + 1 ): A : Tuple =1 if x[i - 1] == y[j - 1] else 0 A : List[Any] =max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match ) A : Union[str, Any] ='' A , A : List[Any] =m, n while i > 0 and j > 0: A : str =1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: A : Optional[Any] =x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": _lowercase : List[Any] ='''AGGTAB''' _lowercase : Optional[Any] ='''GXTXAYB''' _lowercase : List[Any] =4 _lowercase : Optional[int] ='''GTAB''' _lowercase , _lowercase : Optional[Any] =longest_common_subsequence(a, b) print('''len =''', ln, ''', sub-sequence =''', subseq) import doctest doctest.testmod()
661
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
from ...processing_utils import ProcessorMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = ["image_processor", "feature_extractor"] lowercase : List[Any] = "TvltImageProcessor" lowercase : str = "TvltFeatureExtractor" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> List[str]: super().__init__(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) A : int =image_processor A : Optional[int] =feature_extractor def __call__( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : List[Any]=False , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Any , ) -> int: if images is None and audio is None: raise ValueError('You need to specify either an `images` or `audio` input to process.' ) A : Optional[Any] =None if images is not None: A : Optional[int] =self.image_processor(SCREAMING_SNAKE_CASE__ , mask_pixel=SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images_mixed is not None: A : str =self.image_processor(SCREAMING_SNAKE_CASE__ , is_mixed=SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if audio is not None: A : Optional[Any] =self.feature_extractor( SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , sampling_rate=SCREAMING_SNAKE_CASE__ , mask_audio=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str ={} if audio is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) if images is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) if images_mixed_dict is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) return output_dict @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: A : Union[str, Any] =self.image_processor.model_input_names A : List[Any] =self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
from __future__ import annotations _lowercase : int =tuple[int, int, int] _lowercase : Any =tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase _lowercase : List[Any] ='''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- _lowercase : Dict ='''EGZWVONAHDCLFQMSIPJBYUKXTR''' _lowercase : Tuple ='''FOBHMDKEXQNRAULPGSJVTYICZW''' _lowercase : int ='''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- _lowercase : int ={ '''A''': '''N''', '''N''': '''A''', '''B''': '''O''', '''O''': '''B''', '''C''': '''P''', '''P''': '''C''', '''D''': '''Q''', '''Q''': '''D''', '''E''': '''R''', '''R''': '''E''', '''F''': '''S''', '''S''': '''F''', '''G''': '''T''', '''T''': '''G''', '''H''': '''U''', '''U''': '''H''', '''I''': '''V''', '''V''': '''I''', '''J''': '''W''', '''W''': '''J''', '''K''': '''X''', '''X''': '''K''', '''L''': '''Y''', '''Y''': '''L''', '''M''': '''Z''', '''Z''': '''M''', } # -------------------------- extra rotors -------------------------- _lowercase : List[str] ='''RMDJXFUWGISLHVTCQNKYPBEZOA''' _lowercase : Union[str, Any] ='''SGLCPQWZHKXAREONTFBVIYJUDM''' _lowercase : Dict ='''HVSICLTYKQUBXDWAJZOMFGPREN''' _lowercase : str ='''RZWQHFMVDBKICJLNTUXAGYPSOE''' _lowercase : List[str] ='''LFKIJODBEGAMQPXVUHYSTCZRWN''' _lowercase : int ='''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def A__ ( lowercase: RotorPositionT, lowercase: RotorSelectionT, lowercase: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(lowercase ) )) < 3: A : Any =F'Please use 3 unique rotors (not {unique_rotsel})' raise Exception(lowercase ) # Checks if rotor positions are valid A , A , A : Optional[int] =rotpos if not 0 < rotorposa <= len(lowercase ): A : Union[str, Any] =F'First rotor position is not within range of 1..26 ({rotorposa}' raise ValueError(lowercase ) if not 0 < rotorposa <= len(lowercase ): A : Optional[int] =F'Second rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(lowercase ) if not 0 < rotorposa <= len(lowercase ): A : Dict =F'Third rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(lowercase ) # Validates string and returns dict A : Any =_plugboard(lowercase ) return rotpos, rotsel, pbdict def A__ ( lowercase: str ) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(lowercase, lowercase ): A : List[str] =F'Plugboard setting isn\'t type string ({type(lowercase )})' raise TypeError(lowercase ) elif len(lowercase ) % 2 != 0: A : List[Any] =F'Odd number of symbols ({len(lowercase )})' raise Exception(lowercase ) elif pbstring == "": return {} pbstring.replace(' ', '' ) # Checks if all characters are unique A : Dict =set() for i in pbstring: if i not in abc: A : Union[str, Any] =F'\'{i}\' not in list of symbols' raise Exception(lowercase ) elif i in tmppbl: A : Dict =F'Duplicate symbol ({i})' raise Exception(lowercase ) else: tmppbl.add(lowercase ) del tmppbl # Created the dictionary A : Dict ={} for j in range(0, len(lowercase ) - 1, 2 ): A : str =pbstring[j + 1] A : Union[str, Any] =pbstring[j] return pb def A__ ( lowercase: str, lowercase: RotorPositionT, lowercase: RotorSelectionT = (rotora, rotora, rotora), lowercase: str = "", ) -> str: A : Optional[Any] =text.upper() A , A , A : Union[str, Any] =_validator( lowercase, lowercase, plugb.upper() ) A , A , A : Any =rotor_position A , A , A : Dict =rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 A : Union[str, Any] =[] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: A : List[Any] =plugboard[symbol] # rotor ra -------------------------- A : Optional[Any] =abc.index(lowercase ) + rotorposa A : List[str] =rotora[index % len(lowercase )] # rotor rb -------------------------- A : Tuple =abc.index(lowercase ) + rotorposa A : Tuple =rotora[index % len(lowercase )] # rotor rc -------------------------- A : Optional[Any] =abc.index(lowercase ) + rotorposa A : Union[str, Any] =rotora[index % len(lowercase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher A : int =reflector[symbol] # 2nd rotors A : Optional[int] =abc[rotora.index(lowercase ) - rotorposa] A : Optional[Any] =abc[rotora.index(lowercase ) - rotorposa] A : Union[str, Any] =abc[rotora.index(lowercase ) - rotorposa] # 2nd plugboard if symbol in plugboard: A : Union[str, Any] =plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(lowercase ): A : Optional[Any] =0 rotorposa += 1 if rotorposa >= len(lowercase ): A : Union[str, Any] =0 rotorposa += 1 if rotorposa >= len(lowercase ): A : Any =0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(lowercase ) return "".join(lowercase ) if __name__ == "__main__": _lowercase : List[str] ='''This is my Python script that emulates the Enigma machine from WWII.''' _lowercase : Optional[int] =(1, 1, 1) _lowercase : Optional[int] ='''pictures''' _lowercase : int =(rotora, rotora, rotora) _lowercase : Any =enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class SCREAMING_SNAKE_CASE_ ( unittest.TestCase , lowerCAmelCase_ ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[Any]: A : List[str] =load_tool('text-classification' ) self.tool.setup() A : Tuple =load_tool('text-classification' , remote=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Optional[int] =self.tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'positive' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[Any]: A : Optional[int] =self.remote_tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'positive' ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Any =self.tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'positive' ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Optional[int] =self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'positive' )
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : "DiagonalGaussianDistribution" class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : str = True @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE__ : Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE__ : Tuple[int] = (64,) , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : str = "silu" , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 32 , SCREAMING_SNAKE_CASE__ : int = 32 , SCREAMING_SNAKE_CASE__ : float = 0.1_8_2_1_5 , ) -> Optional[Any]: super().__init__() # pass init params to Encoder A : Any =Encoder( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=SCREAMING_SNAKE_CASE__ , down_block_types=SCREAMING_SNAKE_CASE__ , block_out_channels=SCREAMING_SNAKE_CASE__ , layers_per_block=SCREAMING_SNAKE_CASE__ , act_fn=SCREAMING_SNAKE_CASE__ , norm_num_groups=SCREAMING_SNAKE_CASE__ , double_z=SCREAMING_SNAKE_CASE__ , ) # pass init params to Decoder A : Any =Decoder( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=SCREAMING_SNAKE_CASE__ , up_block_types=SCREAMING_SNAKE_CASE__ , block_out_channels=SCREAMING_SNAKE_CASE__ , layers_per_block=SCREAMING_SNAKE_CASE__ , norm_num_groups=SCREAMING_SNAKE_CASE__ , act_fn=SCREAMING_SNAKE_CASE__ , ) A : Union[str, Any] =nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) A : Tuple =nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) A : List[str] =False A : Optional[Any] =False # only relevant if vae tiling is enabled A : Optional[int] =self.config.sample_size A : int =( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) A : Tuple =int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) A : Dict =0.2_5 def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any]=False ) -> Any: if isinstance(SCREAMING_SNAKE_CASE__ , (Encoder, Decoder) ): A : Dict =value def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : bool = True ) -> Any: A : Optional[Any] =use_tiling def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: self.enable_tiling(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: A : Optional[Any] =True def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: A : List[Any] =False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict[str, AttentionProcessor]: A : Optional[Any] ={} def fn_recursive_add_processors(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : torch.nn.Module , SCREAMING_SNAKE_CASE__ : Dict[str, AttentionProcessor] ): if hasattr(SCREAMING_SNAKE_CASE__ , 'set_processor' ): A : Any =module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'{name}.{sub_name}' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return processors def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ) -> List[Any]: A : Optional[Any] =len(self.attn_processors.keys() ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) != count: raise ValueError( f'A dict of processors was passed, but the number of processors {len(SCREAMING_SNAKE_CASE__ )} does not match the' f' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : torch.nn.Module , SCREAMING_SNAKE_CASE__ : List[str] ): if hasattr(SCREAMING_SNAKE_CASE__ , 'set_processor' ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): module.set_processor(SCREAMING_SNAKE_CASE__ ) else: module.set_processor(processor.pop(f'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'{name}.{sub_name}' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for name, module in self.named_children(): fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = True ) -> AutoencoderKLOutput: if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ ) if self.use_slicing and x.shape[0] > 1: A : Union[str, Any] =[self.encoder(SCREAMING_SNAKE_CASE__ ) for x_slice in x.split(1 )] A : Dict =torch.cat(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =self.encoder(SCREAMING_SNAKE_CASE__ ) A : Tuple =self.quant_conv(SCREAMING_SNAKE_CASE__ ) A : List[Any] =DiagonalGaussianDistribution(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =self.post_quant_conv(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.decoder(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE__ ) @apply_forward_hook def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_slicing and z.shape[0] > 1: A : Tuple =[self._decode(SCREAMING_SNAKE_CASE__ ).sample for z_slice in z.split(1 )] A : Dict =torch.cat(SCREAMING_SNAKE_CASE__ ) else: A : List[str] =self._decode(SCREAMING_SNAKE_CASE__ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: A : str =min(a.shape[2] , b.shape[2] , SCREAMING_SNAKE_CASE__ ) for y in range(SCREAMING_SNAKE_CASE__ ): A : str =a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: A : List[Any] =min(a.shape[3] , b.shape[3] , SCREAMING_SNAKE_CASE__ ) for x in range(SCREAMING_SNAKE_CASE__ ): A : Optional[Any] =a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = True ) -> AutoencoderKLOutput: A : int =int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) A : Optional[Any] =int(self.tile_latent_min_size * self.tile_overlap_factor ) A : Dict =self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. A : Dict =[] for i in range(0 , x.shape[2] , SCREAMING_SNAKE_CASE__ ): A : Any =[] for j in range(0 , x.shape[3] , SCREAMING_SNAKE_CASE__ ): A : str =x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] A : Any =self.encoder(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.quant_conv(SCREAMING_SNAKE_CASE__ ) row.append(SCREAMING_SNAKE_CASE__ ) rows.append(SCREAMING_SNAKE_CASE__ ) A : int =[] for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): A : Optional[Any] =[] for j, tile in enumerate(SCREAMING_SNAKE_CASE__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: A : List[str] =self.blend_v(rows[i - 1][j] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if j > 0: A : Any =self.blend_h(row[j - 1] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(SCREAMING_SNAKE_CASE__ , dim=3 ) ) A : List[str] =torch.cat(SCREAMING_SNAKE_CASE__ , dim=2 ) A : int =DiagonalGaussianDistribution(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: A : List[str] =int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) A : str =int(self.tile_sample_min_size * self.tile_overlap_factor ) A : Tuple =self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. A : Optional[int] =[] for i in range(0 , z.shape[2] , SCREAMING_SNAKE_CASE__ ): A : Any =[] for j in range(0 , z.shape[3] , SCREAMING_SNAKE_CASE__ ): A : Any =z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] A : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE__ ) A : str =self.decoder(SCREAMING_SNAKE_CASE__ ) row.append(SCREAMING_SNAKE_CASE__ ) rows.append(SCREAMING_SNAKE_CASE__ ) A : List[Any] =[] for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): A : Optional[Any] =[] for j, tile in enumerate(SCREAMING_SNAKE_CASE__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: A : Optional[int] =self.blend_v(rows[i - 1][j] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if j > 0: A : Optional[Any] =self.blend_h(row[j - 1] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(SCREAMING_SNAKE_CASE__ , dim=3 ) ) A : Optional[Any] =torch.cat(SCREAMING_SNAKE_CASE__ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : torch.FloatTensor , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None , ) -> Union[DecoderOutput, torch.FloatTensor]: A : List[Any] =sample A : str =self.encode(SCREAMING_SNAKE_CASE__ ).latent_dist if sample_posterior: A : Tuple =posterior.sample(generator=SCREAMING_SNAKE_CASE__ ) else: A : Tuple =posterior.mode() A : str =self.decode(SCREAMING_SNAKE_CASE__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE__ )
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
import baseaa def A__ ( lowercase: str ) -> bytes: return baseaa.baaencode(string.encode('utf-8' ) ) def A__ ( lowercase: bytes ) -> str: return baseaa.baadecode(lowercase ).decode('utf-8' ) if __name__ == "__main__": _lowercase : Tuple ='''Hello World!''' _lowercase : Dict =baseaa_encode(test) print(encoded) _lowercase : int =baseaa_decode(encoded) print(decoded)
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": _lowercase : str =argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--original_config_file''', type=str, required=True, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--image_size''', default=5_1_2, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') def A__ ( lowercase: Union[str, Any] ) -> Any: if string == "True": return True elif string == "False": return False else: raise ValueError(F'could not parse string as bool {string}' ) parser.add_argument( '''--use_linear_projection''', help='''Override for use linear projection''', required=False, type=parse_bool ) parser.add_argument('''--cross_attention_dim''', help='''Override for cross attention_dim''', required=False, type=int) _lowercase : List[str] =parser.parse_args() _lowercase : Optional[int] =download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase : Any ={ '''configuration_mobilebert''': [ '''MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileBertConfig''', '''MobileBertOnnxConfig''', ], '''tokenization_mobilebert''': ['''MobileBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Any =['''MobileBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] =[ '''MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileBertForMaskedLM''', '''MobileBertForMultipleChoice''', '''MobileBertForNextSentencePrediction''', '''MobileBertForPreTraining''', '''MobileBertForQuestionAnswering''', '''MobileBertForSequenceClassification''', '''MobileBertForTokenClassification''', '''MobileBertLayer''', '''MobileBertModel''', '''MobileBertPreTrainedModel''', '''load_tf_weights_in_mobilebert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] =[ '''TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileBertForMaskedLM''', '''TFMobileBertForMultipleChoice''', '''TFMobileBertForNextSentencePrediction''', '''TFMobileBertForPreTraining''', '''TFMobileBertForQuestionAnswering''', '''TFMobileBertForSequenceClassification''', '''TFMobileBertForTokenClassification''', '''TFMobileBertMainLayer''', '''TFMobileBertModel''', '''TFMobileBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys _lowercase : List[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def A__ ( ) -> tuple[list[int], int]: A : Optional[int] =[randint(-1_000, 1_000 ) for i in range(10 )] A : List[Any] =randint(-5_000, 5_000 ) return (arr, r) _lowercase : int =make_dataset() def A__ ( lowercase: list[int], lowercase: int ) -> tuple[int, ...]: for triplet in permutations(lowercase, 3 ): if sum(lowercase ) == target: return tuple(sorted(lowercase ) ) return (0, 0, 0) def A__ ( lowercase: list[int], lowercase: int ) -> tuple[int, int, int]: arr.sort() A : Optional[int] =len(lowercase ) for i in range(n - 1 ): A , A : Union[str, Any] =i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def A__ ( ) -> tuple[float, float]: A : Optional[Any] ='\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n' A : Tuple ='\ntriplet_sum1(*dataset)\n' A : Optional[int] ='\ntriplet_sum2(*dataset)\n' A : Dict =repeat(setup=lowercase, stmt=lowercase, repeat=5, number=10_000 ) A : Optional[int] =repeat(setup=lowercase, stmt=lowercase, repeat=5, number=10_000 ) return (min(lowercase ), min(lowercase )) if __name__ == "__main__": from doctest import testmod testmod() _lowercase : List[Any] =solution_times() print(f'''The time for naive implementation is {times[0]}.''') print(f'''The time for optimized implementation is {times[1]}.''')
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
_lowercase : str =9.8_0_6_6_5 def A__ ( lowercase: float, lowercase: float, lowercase: float = g ) -> float: if fluid_density <= 0: raise ValueError('Impossible fluid density' ) if volume < 0: raise ValueError('Impossible Object volume' ) if gravity <= 0: raise ValueError('Impossible Gravity' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
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 ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowercase : Dict =logging.get_logger(__name__) def A__ ( lowercase: str ) -> Tuple: A : List[str] =SwinConfig.from_pretrained( 'microsoft/swin-tiny-patch4-window7-224', out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) A : List[str] =MaskFormerConfig(backbone_config=lowercase ) A : Tuple ='huggingface/label-files' if "ade20k-full" in model_name: # this should be ok A : Tuple =847 A : int ='maskformer-ade20k-full-id2label.json' elif "ade" in model_name: # this should be ok A : str =150 A : Tuple ='ade20k-id2label.json' elif "coco-stuff" in model_name: # this should be ok A : Union[str, Any] =171 A : Dict ='maskformer-coco-stuff-id2label.json' elif "coco" in model_name: # TODO A : int =133 A : int ='coco-panoptic-id2label.json' elif "cityscapes" in model_name: # this should be ok A : List[Any] =19 A : Tuple ='cityscapes-id2label.json' elif "vistas" in model_name: # this should be ok A : str =65 A : Union[str, Any] ='mapillary-vistas-id2label.json' A : Union[str, Any] =json.load(open(hf_hub_download(lowercase, lowercase, repo_type='dataset' ), 'r' ) ) A : Dict ={int(lowercase ): v for k, v in idalabel.items()} return config def A__ ( lowercase: Any ) -> Tuple: A : Union[str, Any] =[] # stem # fmt: off rename_keys.append(('backbone.patch_embed.proj.weight', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.proj.bias', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'model.pixel_level_module.encoder.model.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'model.pixel_level_module.encoder.model.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.layers.{i}.blocks.{j}.norm1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_index', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight') ) rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias') ) if i < 3: rename_keys.append((F'backbone.layers.{i}.downsample.reduction.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight') ) rename_keys.append((F'backbone.layers.{i}.downsample.norm.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight') ) rename_keys.append((F'backbone.layers.{i}.downsample.norm.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias') ) rename_keys.append((F'backbone.norm{i}.weight', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.weight') ) rename_keys.append((F'backbone.norm{i}.bias', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.bias') ) # FPN rename_keys.append(('sem_seg_head.layer_4.weight', 'model.pixel_level_module.decoder.fpn.stem.0.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.weight', 'model.pixel_level_module.decoder.fpn.stem.1.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.bias', 'model.pixel_level_module.decoder.fpn.stem.1.bias') ) for source_index, target_index in zip(range(3, 0, -1 ), range(0, 3 ) ): rename_keys.append((F'sem_seg_head.adapter_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight') ) rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight') ) rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias') ) rename_keys.append((F'sem_seg_head.layer_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight') ) rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight') ) rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias') ) rename_keys.append(('sem_seg_head.mask_features.weight', 'model.pixel_level_module.decoder.mask_projection.weight') ) rename_keys.append(('sem_seg_head.mask_features.bias', 'model.pixel_level_module.decoder.mask_projection.bias') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias') ) # cross-attention out projection rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias') ) # MLP 1 rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight', F'model.transformer_module.decoder.layers.{idx}.fc1.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias', F'model.transformer_module.decoder.layers.{idx}.fc1.bias') ) # MLP 2 rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight', F'model.transformer_module.decoder.layers.{idx}.fc2.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias', F'model.transformer_module.decoder.layers.{idx}.fc2.bias') ) # layernorm 1 (self-attention layernorm) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias') ) # layernorm 3 (final layernorm) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight') ) rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.weight', 'model.transformer_module.decoder.layernorm.weight') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.bias', 'model.transformer_module.decoder.layernorm.bias') ) # heads on top rename_keys.append(('sem_seg_head.predictor.query_embed.weight', 'model.transformer_module.queries_embedder.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.weight', 'model.transformer_module.input_projection.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.bias', 'model.transformer_module.input_projection.bias') ) rename_keys.append(('sem_seg_head.predictor.class_embed.weight', 'class_predictor.weight') ) rename_keys.append(('sem_seg_head.predictor.class_embed.bias', 'class_predictor.bias') ) for i in range(3 ): rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.weight', F'mask_embedder.{i}.0.weight') ) rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.bias', F'mask_embedder.{i}.0.bias') ) # fmt: on return rename_keys def A__ ( lowercase: Dict, lowercase: Dict, lowercase: Optional[int] ) -> Optional[Any]: A : str =dct.pop(lowercase ) A : List[Any] =val def A__ ( lowercase: int, lowercase: Dict ) -> str: A : Dict =[int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): A : Tuple =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) A : Optional[Any] =state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.weight' ) A : str =state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A : Tuple =in_proj_weight[:dim, :] A : Any =in_proj_bias[: dim] A : Optional[Any] =in_proj_weight[ dim : dim * 2, : ] A : Optional[int] =in_proj_bias[ dim : dim * 2 ] A : int =in_proj_weight[ -dim :, : ] A : List[Any] =in_proj_bias[-dim :] # fmt: on def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> Dict: # fmt: off A : Any =config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) A : Any =state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight' ) A : int =state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict A : Optional[Any] =in_proj_weight[: hidden_size, :] A : Union[str, Any] =in_proj_bias[:config.hidden_size] A : Optional[Any] =in_proj_weight[hidden_size : hidden_size * 2, :] A : List[Any] =in_proj_bias[hidden_size : hidden_size * 2] A : List[str] =in_proj_weight[-hidden_size :, :] A : int =in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) A : Union[str, Any] =state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight' ) A : List[Any] =state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict A : Optional[int] =in_proj_weight[: hidden_size, :] A : Any =in_proj_bias[:config.hidden_size] A : Dict =in_proj_weight[hidden_size : hidden_size * 2, :] A : int =in_proj_bias[hidden_size : hidden_size * 2] A : Any =in_proj_weight[-hidden_size :, :] A : Dict =in_proj_bias[-hidden_size :] # fmt: on def A__ ( ) -> torch.Tensor: A : Tuple ='http://images.cocodataset.org/val2017/000000039769.jpg' A : Union[str, Any] =Image.open(requests.get(lowercase, stream=lowercase ).raw ) return im @torch.no_grad() def A__ ( lowercase: str, lowercase: str, lowercase: str, lowercase: bool = False ) -> Dict: A : Union[str, Any] =get_maskformer_config(lowercase ) # load original state_dict with open(lowercase, 'rb' ) as f: A : Optional[Any] =pickle.load(lowercase ) A : Optional[int] =data['model'] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys A : List[str] =create_rename_keys(lowercase ) for src, dest in rename_keys: rename_key(lowercase, lowercase, lowercase ) read_in_swin_q_k_v(lowercase, config.backbone_config ) read_in_decoder_q_k_v(lowercase, lowercase ) # update to torch tensors for key, value in state_dict.items(): A : Dict =torch.from_numpy(lowercase ) # load 🤗 model A : int =MaskFormerForInstanceSegmentation(lowercase ) model.eval() for name, param in model.named_parameters(): print(lowercase, param.shape ) A , A : List[Any] =model.load_state_dict(lowercase, strict=lowercase ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(lowercase ) == 0, F'Unexpected keys: {unexpected_keys}' # verify results A : Dict =prepare_img() if "vistas" in model_name: A : Optional[int] =65 elif "cityscapes" in model_name: A : int =65_535 else: A : Optional[int] =255 A : List[str] =True if 'ade' in model_name else False A : Optional[int] =MaskFormerImageProcessor(ignore_index=lowercase, reduce_labels=lowercase ) A : Tuple =image_processor(lowercase, return_tensors='pt' ) A : Optional[Any] =model(**lowercase ) print('Logits:', outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": A : Optional[Any] =torch.tensor( [[3.63_53, -4.47_70, -2.60_65], [0.50_81, -4.23_94, -3.53_43], [2.19_09, -5.03_53, -1.93_23]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3], lowercase, atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'Saving model and image processor to {pytorch_dump_folder_path}' ) Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) image_processor.save_pretrained(lowercase ) if push_to_hub: print('Pushing model and image processor to the hub...' ) model.push_to_hub(F'nielsr/{model_name}' ) image_processor.push_to_hub(F'nielsr/{model_name}' ) if __name__ == "__main__": _lowercase : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''maskformer-swin-tiny-ade''', type=str, help=('''Name of the MaskFormer model you\'d like to convert''',), ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl''', type=str, help='''Path to the original state dict (.pth file).''', ) 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.''' ) _lowercase : int =parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _lowercase : Tuple =2_9_9_7_9_2_4_5_8 # Symbols _lowercase , _lowercase , _lowercase , _lowercase : Any =symbols('''ct x y z''') def A__ ( lowercase: float ) -> float: if velocity > c: raise ValueError('Speed must not exceed light speed 299,792,458 [m/s]!' ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError('Speed must be greater than or equal to 1!' ) return velocity / c def A__ ( lowercase: float ) -> float: return 1 / sqrt(1 - beta(lowercase ) ** 2 ) def A__ ( lowercase: float ) -> np.ndarray: return np.array( [ [gamma(lowercase ), -gamma(lowercase ) * beta(lowercase ), 0, 0], [-gamma(lowercase ) * beta(lowercase ), gamma(lowercase ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def A__ ( lowercase: float, lowercase: np.ndarray | None = None ) -> np.ndarray: # Ensure event is not empty if event is None: A : List[str] =np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _lowercase : Dict =transform(2_9_9_7_9_2_4_5) print('''Example of four vector: ''') print(f'''ct\' = {four_vector[0]}''') print(f'''x\' = {four_vector[1]}''') print(f'''y\' = {four_vector[2]}''') print(f'''z\' = {four_vector[3]}''') # Substitute symbols with numerical values _lowercase : Dict ={ct: c, x: 1, y: 1, z: 1} _lowercase : Dict =[four_vector[i].subs(sub_dict) for i in range(4)] print(f'''\n{numerical_vector}''')
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, 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=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def A__ ( lowercase: Optional[Any], lowercase: List[Any]=False ) -> Dict: A : Optional[Any] =OmegaConf.load(lowercase ) if display: print(yaml.dump(OmegaConf.to_container(lowercase ) ) ) return config def A__ ( lowercase: Union[str, Any], lowercase: str=None, lowercase: List[Any]=None ) -> List[Any]: if conf_path is None: A : List[str] ='./model_checkpoints/vqgan_only.yaml' A : Any =load_config(lowercase, display=lowercase ) A : Tuple =VQModel(**config.model.params ) if ckpt_path is None: A : Union[str, Any] ='./model_checkpoints/vqgan_only.pt' A : Optional[int] =torch.load(lowercase, map_location=lowercase ) if ".ckpt" in ckpt_path: A : Optional[int] =sd['state_dict'] model.load_state_dict(lowercase, strict=lowercase ) model.to(lowercase ) del sd return model def A__ ( lowercase: int, lowercase: Tuple ) -> List[str]: A , A , A : List[str] =model.encode(lowercase ) print(F'VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}' ) A : Dict =model.decode(lowercase ) return xrec def A__ ( lowercase: Optional[int], lowercase: int=False ) -> Dict: A , A : Any =string.rsplit('.', 1 ) if reload: A : int =importlib.import_module(lowercase ) importlib.reload(lowercase ) return getattr(importlib.import_module(lowercase, package=lowercase ), cls ) def A__ ( lowercase: List[Any] ) -> int: if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params', {} ) ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Union[str, Any]=True, lowercase: Any=True ) -> List[str]: A : Dict =instantiate_from_config(lowercase ) if sd is not None: model.load_state_dict(lowercase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def A__ ( lowercase: Optional[Any], lowercase: Tuple, lowercase: Union[str, Any], lowercase: int ) -> List[str]: # load the specified checkpoint if ckpt: A : str =torch.load(lowercase, map_location='cpu' ) A : str =pl_sd['global_step'] print(F'loaded model from global step {global_step}.' ) else: A : Dict ={'state_dict': None} A : Any =None A : Optional[Any] =load_model_from_config(config.model, pl_sd['state_dict'], gpu=lowercase, eval_mode=lowercase )['model'] return model, global_step
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A : Optional[int] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : str =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : Optional[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A : Tuple ='base imports' if key == 'none' else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\n'.join(F'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
661
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowercase : Union[str, Any] =logging.get_logger(__name__) _lowercase : Optional[int] ={ '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = "deformable_detr" lowercase : Optional[int] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : int=3_00 , SCREAMING_SNAKE_CASE__ : int=10_24 , SCREAMING_SNAKE_CASE__ : List[str]=6 , SCREAMING_SNAKE_CASE__ : Tuple=10_24 , SCREAMING_SNAKE_CASE__ : Any=8 , SCREAMING_SNAKE_CASE__ : Any=6 , SCREAMING_SNAKE_CASE__ : int=10_24 , SCREAMING_SNAKE_CASE__ : List[Any]=8 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict="relu" , SCREAMING_SNAKE_CASE__ : Any=2_56 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : Tuple=1.0 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : Optional[int]="sine" , SCREAMING_SNAKE_CASE__ : Tuple="resnet50" , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : int=4 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : int=3_00 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : str=1 , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : List[Any]=5 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.2_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> Optional[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 : Optional[int] =CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : int =backbone_config.get('model_type' ) A : Optional[Any] =CONFIG_MAPPING[backbone_model_type] A : Dict =config_class.from_dict(SCREAMING_SNAKE_CASE__ ) A : str =use_timm_backbone A : Union[str, Any] =backbone_config A : Dict =num_channels A : Dict =num_queries A : List[Any] =max_position_embeddings A : Optional[int] =d_model A : Optional[Any] =encoder_ffn_dim A : Tuple =encoder_layers A : Union[str, Any] =encoder_attention_heads A : Optional[int] =decoder_ffn_dim A : Union[str, Any] =decoder_layers A : Tuple =decoder_attention_heads A : Optional[Any] =dropout A : Dict =attention_dropout A : Dict =activation_dropout A : Any =activation_function A : str =init_std A : Any =init_xavier_std A : Optional[Any] =encoder_layerdrop A : Union[str, Any] =auxiliary_loss A : List[str] =position_embedding_type A : List[str] =backbone A : int =use_pretrained_backbone A : int =dilation # deformable attributes A : List[Any] =num_feature_levels A : Optional[Any] =encoder_n_points A : List[str] =decoder_n_points A : Optional[Any] =two_stage A : List[str] =two_stage_num_proposals A : Optional[int] =with_box_refine if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher A : Optional[Any] =class_cost A : Tuple =bbox_cost A : Optional[Any] =giou_cost # Loss coefficients A : Union[str, Any] =mask_loss_coefficient A : Dict =dice_loss_coefficient A : List[str] =bbox_loss_coefficient A : Optional[int] =giou_loss_coefficient A : Any =eos_coefficient A : Any =focal_alpha A : Tuple =disable_custom_kernels super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> int: return self.d_model def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: A : List[Any] =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: A : str =self.backbone_config.to_dict() A : Dict =self.__class__.model_type return output
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
from sklearn.metrics import fa_score import datasets _lowercase : int =''' The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) ''' _lowercase : List[str] =''' Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives. - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {\'f1\': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results[\'f1\'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results[\'f1\'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro") >>> print(round(results[\'f1\'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'f1\': array([0.8, 0. , 0. ])} ''' _lowercase : str =''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE_ ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict="binary" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ) -> Optional[Any]: A : int =fa_score( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , pos_label=SCREAMING_SNAKE_CASE__ , average=SCREAMING_SNAKE_CASE__ , sample_weight=SCREAMING_SNAKE_CASE__ ) return {"f1": float(SCREAMING_SNAKE_CASE__ ) if score.size == 1 else score}
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> str: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowercase : Union[str, Any] =logging.get_logger(__name__) _lowercase : Tuple ={ '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } _lowercase : List[str] =[ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: List[Any], lowercase: Union[str, Any], lowercase: Optional[int] ) -> str: for attribute in key.split('.' ): A : List[Any] =getattr(lowercase, lowercase ) if weight_type is not None: A : Optional[int] =getattr(lowercase, lowercase ).shape else: A : List[Any] =hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": A : List[str] =value elif weight_type == "weight_g": A : Optional[Any] =value elif weight_type == "weight_v": A : List[str] =value elif weight_type == "bias": A : List[str] =value else: A : str =value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A__ ( lowercase: int, lowercase: List[str] ) -> Dict: A : str =[] A : List[Any] =fairseq_model.state_dict() A : Optional[int] =hf_model.feature_extractor A : Optional[int] =hf_model.adapter for name, value in fairseq_dict.items(): A : str =False if "conv_layers" in name: load_conv_layer( lowercase, lowercase, lowercase, lowercase, hf_model.config.feat_extract_norm == 'group', ) A : List[str] =True elif any(x in name for x in ['adaptor', 'w2v_encoder.proj.', 'w2v_proj_ln.'] ): load_adapter(lowercase, lowercase, lowercase, lowercase ) A : List[str] =True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: A : str =True if "*" in mapped_key: A : int =name.split(lowercase )[0].split('.' )[-2] A : List[str] =mapped_key.replace('*', lowercase ) if "weight_g" in name: A : List[Any] ='weight_g' elif "weight_v" in name: A : Optional[int] ='weight_v' elif "bias" in name: A : List[str] ='bias' elif "weight" in name: A : Any ='weight' else: A : Optional[int] =None set_recursively(lowercase, lowercase, lowercase, lowercase, lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(F'Unused weights: {unused_weights}' ) def A__ ( lowercase: List[str], lowercase: List[str], lowercase: Tuple, lowercase: Any, lowercase: Dict ) -> List[Any]: A : str =full_name.split('conv_layers.' )[-1] A : List[Any] =name.split('.' ) A : Optional[Any] =int(items[0] ) A : int =int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) A : Optional[int] =value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) A : Union[str, Any] =value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) A : Any =value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) A : Any =value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowercase ) def A__ ( lowercase: Tuple, lowercase: int, lowercase: List[str], lowercase: Optional[Any] ) -> str: A : Union[str, Any] =full_name.split('adaptor.' )[-1] A : Tuple =name.split('.' ) if items[1].isdigit(): A : Any =int(items[1] ) else: A : List[str] =None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.' A : Optional[int] =value logger.info(F'Adapter proj layer norm bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.' A : Optional[Any] =value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.' A : int =value logger.info(F'Adapter proj layer bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.' A : Optional[int] =value logger.info(F'Adapter proj layer weight was initialized from {full_name}.' ) elif isinstance(lowercase, lowercase ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.' A : List[str] =value logger.info(F'Adapter layer {layer_id} bias was initialized from {full_name}.' ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.' A : Optional[int] =value logger.info(F'Adapter layer {layer_id} bias was initialized from {full_name}.' ) else: unused_weights.append(lowercase ) def A__ ( lowercase: Optional[Any] ) -> Optional[Any]: A , A : str =emb.weight.shape A : List[Any] =nn.Linear(lowercase, lowercase, bias=lowercase ) A : int =emb.weight.data return lin_layer @torch.no_grad() def A__ ( lowercase: Any, lowercase: str, lowercase: List[str], lowercase: int, lowercase: Optional[Any], lowercase: List[Any], lowercase: Optional[int], lowercase: int, lowercase: str, lowercase: List[Any], lowercase: str, ) -> Optional[int]: A : Optional[int] =WavaVecaConfig.from_pretrained( lowercase, add_adapter=lowercase, adapter_stride=lowercase, adapter_kernel_size=lowercase, use_auth_token=lowercase, output_hidden_size=lowercase, ) A : int =MBartConfig.from_pretrained(lowercase ) # load model A , A , A : List[Any] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={ 'config_yaml': config_yaml_path, 'data': '/'.join(dict_path.split('/' )[:-1] ), 'w2v_path': checkpoint_path, 'load_pretrained_decoder_from': None, }, ) A : Union[str, Any] =model[0].eval() # load feature extractor A : Tuple =WavaVecaFeatureExtractor.from_pretrained(lowercase, use_auth_token=lowercase ) # set weights for wav2vec2 encoder A : str =WavaVecaModel(lowercase ) recursively_load_weights_wavaveca(model.encoder, lowercase ) # load decoder weights A : List[str] =MBartForCausalLM(lowercase ) A , A : Optional[Any] =hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=lowercase ) logger.warning(F'The following keys are missing when loading the decoder weights: {missing_keys}' ) logger.warning(F'The following keys are unexpected when loading the decoder weights: {unexpected_keys}' ) A : Optional[Any] =SpeechEncoderDecoderModel(encoder=lowercase, decoder=lowercase ) A : Any =False A : Optional[int] =MBartaaTokenizer(lowercase ) tokenizer.save_pretrained(lowercase ) A : int =hf_wavavec.config.to_dict() A : Dict =tokenizer.pad_token_id A : str =tokenizer.bos_token_id A : Tuple =tokenizer.eos_token_id A : Tuple ='mbart50' A : Any ='wav2vec2' A : Tuple =tokenizer.eos_token_id A : List[Any] =250_004 A : Optional[int] =tokenizer.eos_token_id A : Any =SpeechEncoderDecoderConfig.from_dict(lowercase ) hf_wavavec.save_pretrained(lowercase ) feature_extractor.save_pretrained(lowercase ) if __name__ == "__main__": _lowercase : int =argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_yaml_path''', default=None, type=str, help='''Path to yaml file of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-xls-r-1b''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/mbart-large-50-one-to-many-mmt''', type=str, help='''Path to hf decoder checkpoint config''', ) parser.add_argument('''--add_adapter''', default=True, type=bool, help='''whethere to add model adapter layers''') parser.add_argument('''--adapter_stride''', default=2, type=int, help='''stride of adapter layers''') parser.add_argument('''--adapter_kernel_size''', default=3, type=int, help='''kernel size of adapter layers''') parser.add_argument('''--encoder_output_dim''', default=1_0_2_4, type=int, help='''encoder output dim''') parser.add_argument('''--start_token_id''', default=2_5_0_0_0_4, type=int, help='''`decoder_start_token_id` of model config''') _lowercase : List[str] =parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) _lowercase : List[Any] =logging.get_logger(__name__) _lowercase : Dict =OrderedDict( [ ('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''), ('''beit''', '''BeitFeatureExtractor'''), ('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''), ('''clap''', '''ClapFeatureExtractor'''), ('''clip''', '''CLIPFeatureExtractor'''), ('''clipseg''', '''ViTFeatureExtractor'''), ('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''), ('''convnext''', '''ConvNextFeatureExtractor'''), ('''cvt''', '''ConvNextFeatureExtractor'''), ('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''), ('''data2vec-vision''', '''BeitFeatureExtractor'''), ('''deformable_detr''', '''DeformableDetrFeatureExtractor'''), ('''deit''', '''DeiTFeatureExtractor'''), ('''detr''', '''DetrFeatureExtractor'''), ('''dinat''', '''ViTFeatureExtractor'''), ('''donut-swin''', '''DonutFeatureExtractor'''), ('''dpt''', '''DPTFeatureExtractor'''), ('''encodec''', '''EncodecFeatureExtractor'''), ('''flava''', '''FlavaFeatureExtractor'''), ('''glpn''', '''GLPNFeatureExtractor'''), ('''groupvit''', '''CLIPFeatureExtractor'''), ('''hubert''', '''Wav2Vec2FeatureExtractor'''), ('''imagegpt''', '''ImageGPTFeatureExtractor'''), ('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''), ('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''), ('''levit''', '''LevitFeatureExtractor'''), ('''maskformer''', '''MaskFormerFeatureExtractor'''), ('''mctct''', '''MCTCTFeatureExtractor'''), ('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''), ('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''), ('''mobilevit''', '''MobileViTFeatureExtractor'''), ('''nat''', '''ViTFeatureExtractor'''), ('''owlvit''', '''OwlViTFeatureExtractor'''), ('''perceiver''', '''PerceiverFeatureExtractor'''), ('''poolformer''', '''PoolFormerFeatureExtractor'''), ('''regnet''', '''ConvNextFeatureExtractor'''), ('''resnet''', '''ConvNextFeatureExtractor'''), ('''segformer''', '''SegformerFeatureExtractor'''), ('''sew''', '''Wav2Vec2FeatureExtractor'''), ('''sew-d''', '''Wav2Vec2FeatureExtractor'''), ('''speech_to_text''', '''Speech2TextFeatureExtractor'''), ('''speecht5''', '''SpeechT5FeatureExtractor'''), ('''swiftformer''', '''ViTFeatureExtractor'''), ('''swin''', '''ViTFeatureExtractor'''), ('''swinv2''', '''ViTFeatureExtractor'''), ('''table-transformer''', '''DetrFeatureExtractor'''), ('''timesformer''', '''VideoMAEFeatureExtractor'''), ('''tvlt''', '''TvltFeatureExtractor'''), ('''unispeech''', '''Wav2Vec2FeatureExtractor'''), ('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''), ('''van''', '''ConvNextFeatureExtractor'''), ('''videomae''', '''VideoMAEFeatureExtractor'''), ('''vilt''', '''ViltFeatureExtractor'''), ('''vit''', '''ViTFeatureExtractor'''), ('''vit_mae''', '''ViTFeatureExtractor'''), ('''vit_msn''', '''ViTFeatureExtractor'''), ('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''), ('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''), ('''wavlm''', '''Wav2Vec2FeatureExtractor'''), ('''whisper''', '''WhisperFeatureExtractor'''), ('''xclip''', '''CLIPFeatureExtractor'''), ('''yolos''', '''YolosFeatureExtractor'''), ] ) _lowercase : int =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def A__ ( lowercase: str ) -> Union[str, Any]: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: A : Optional[Any] =model_type_to_module_name(lowercase ) A : Union[str, Any] =importlib.import_module(F'.{module_name}', 'transformers.models' ) try: return getattr(lowercase, lowercase ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(lowercase, '__name__', lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. A : Optional[Any] =importlib.import_module('transformers' ) if hasattr(lowercase, lowercase ): return getattr(lowercase, lowercase ) return None def A__ ( lowercase: Union[str, os.PathLike], lowercase: Optional[Union[str, os.PathLike]] = None, lowercase: bool = False, lowercase: bool = False, lowercase: Optional[Dict[str, str]] = None, lowercase: Optional[Union[bool, str]] = None, lowercase: Optional[str] = None, lowercase: bool = False, **lowercase: Union[str, Any], ) -> Dict: A : Dict =get_file_from_repo( lowercase, lowercase, cache_dir=lowercase, force_download=lowercase, resume_download=lowercase, proxies=lowercase, use_auth_token=lowercase, revision=lowercase, local_files_only=lowercase, ) if resolved_config_file is None: logger.info( 'Could not locate the feature extractor configuration file, will try to use the model config instead.' ) return {} with open(lowercase, encoding='utf-8' ) as reader: return json.load(lowercase ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str ) -> Any: raise EnvironmentError( 'AutoFeatureExtractor is designed to be instantiated ' 'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( cls : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: A : Optional[int] =kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) A : List[str] =kwargs.pop('trust_remote_code' , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =True A , A : Union[str, Any] =FeatureExtractionMixin.get_feature_extractor_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =config_dict.get('feature_extractor_type' , SCREAMING_SNAKE_CASE__ ) A : Dict =None if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ): A : Union[str, Any] =config_dict['auto_map']['AutoFeatureExtractor'] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Any =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # It could be in `config.feature_extractor_type`` A : Union[str, Any] =getattr(SCREAMING_SNAKE_CASE__ , 'feature_extractor_type' , SCREAMING_SNAKE_CASE__ ) if hasattr(SCREAMING_SNAKE_CASE__ , 'auto_map' ) and "AutoFeatureExtractor" in config.auto_map: A : Union[str, Any] =config.auto_map['AutoFeatureExtractor'] if feature_extractor_class is not None: A : Tuple =feature_extractor_class_from_name(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =feature_extractor_auto_map is not None A : str =feature_extractor_class is not None or type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING A : List[Any] =resolve_trust_remote_code( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if has_remote_code and trust_remote_code: A : Any =get_class_from_dynamic_module( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Any =kwargs.pop('code_revision' , SCREAMING_SNAKE_CASE__ ) if os.path.isdir(SCREAMING_SNAKE_CASE__ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING: A : Dict =FEATURE_EXTRACTOR_MAPPING[type(SCREAMING_SNAKE_CASE__ )] return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) raise ValueError( f'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' f'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: FEATURE_EXTRACTOR_MAPPING.register(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
661
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 ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) _lowercase : List[Any] ={ '''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''', '''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''', '''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''', '''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''', '''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''', '''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''', '''mask_downscaling.0''': '''mask_embed.conv1''', '''mask_downscaling.1''': '''mask_embed.layer_norm1''', '''mask_downscaling.3''': '''mask_embed.conv2''', '''mask_downscaling.4''': '''mask_embed.layer_norm2''', '''mask_downscaling.6''': '''mask_embed.conv3''', '''point_embeddings''': '''point_embed''', '''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''', '''image_encoder''': '''vision_encoder''', '''neck.0''': '''neck.conv1''', '''neck.1''': '''neck.layer_norm1''', '''neck.2''': '''neck.conv2''', '''neck.3''': '''neck.layer_norm2''', '''patch_embed.proj''': '''patch_embed.projection''', '''.norm''': '''.layer_norm''', '''blocks''': '''layers''', } def A__ ( lowercase: List[Any] ) -> Dict: A : int ={} state_dict.pop('pixel_mean', lowercase ) state_dict.pop('pixel_std', lowercase ) A : Any =r'.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*' for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: A : Dict =key.replace(lowercase, lowercase ) if re.match(lowercase, lowercase ): A : str =int(re.match(lowercase, lowercase ).group(2 ) ) if layer_nb == 0: A : Dict =key.replace('layers.0', 'proj_in' ) elif layer_nb == 1: A : List[str] =key.replace('layers.1', 'layers.0' ) elif layer_nb == 2: A : Optional[Any] =key.replace('layers.2', 'proj_out' ) A : Tuple =value A : Dict =model_state_dict[ 'prompt_encoder.shared_embedding.positional_embedding' ] return model_state_dict def A__ ( lowercase: Optional[Any], lowercase: List[str], lowercase: Any, lowercase: Tuple="ybelkada/segment-anything" ) -> Union[str, Any]: A : Optional[int] =hf_hub_download(lowercase, F'checkpoints/{model_name}.pth' ) if "sam_vit_b" in model_name: A : Dict =SamConfig() elif "sam_vit_l" in model_name: A : Optional[Any] =SamVisionConfig( hidden_size=1_024, num_hidden_layers=24, num_attention_heads=16, global_attn_indexes=[5, 11, 17, 23], ) A : Any =SamConfig( vision_config=lowercase, ) elif "sam_vit_h" in model_name: A : Tuple =SamVisionConfig( hidden_size=1_280, num_hidden_layers=32, num_attention_heads=16, global_attn_indexes=[7, 15, 23, 31], ) A : Any =SamConfig( vision_config=lowercase, ) A : int =torch.load(lowercase, map_location='cpu' ) A : List[Any] =replace_keys(lowercase ) A : int =SamImageProcessor() A : Optional[Any] =SamProcessor(image_processor=lowercase ) A : Optional[int] =SamModel(lowercase ) hf_model.load_state_dict(lowercase ) A : Tuple =hf_model.to('cuda' ) A : Tuple ='https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png' A : List[Any] =Image.open(requests.get(lowercase, stream=lowercase ).raw ).convert('RGB' ) A : List[Any] =[[[400, 650]]] A : List[str] =[[1]] A : int =processor(images=np.array(lowercase ), return_tensors='pt' ).to('cuda' ) with torch.no_grad(): A : Optional[Any] =hf_model(**lowercase ) A : List[Any] =output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.5_79_89_02_51_15_96_68 A : Any =processor( images=np.array(lowercase ), input_points=lowercase, input_labels=lowercase, return_tensors='pt' ).to('cuda' ) with torch.no_grad(): A : List[str] =hf_model(**lowercase ) A : Tuple =output.iou_scores.squeeze() assert scores[-1].item() == 0.97_12_60_30_92_19_36_04 A : List[Any] =((75, 275, 1_725, 850),) A : Union[str, Any] =processor(images=np.array(lowercase ), input_boxes=lowercase, return_tensors='pt' ).to('cuda' ) with torch.no_grad(): A : List[Any] =hf_model(**lowercase ) A : List[str] =output.iou_scores.squeeze() assert scores[-1].item() == 0.86_86_01_56_05_92_65_14 # Test with 2 points and 1 image. A : Optional[int] =[[[400, 650], [800, 650]]] A : Tuple =[[1, 1]] A : str =processor( images=np.array(lowercase ), input_points=lowercase, input_labels=lowercase, return_tensors='pt' ).to('cuda' ) with torch.no_grad(): A : Optional[Any] =hf_model(**lowercase ) A : List[str] =output.iou_scores.squeeze() assert scores[-1].item() == 0.99_36_04_77_92_43_46_92 if __name__ == "__main__": _lowercase : str =argparse.ArgumentParser() _lowercase : Tuple =['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195'''] parser.add_argument( '''--model_name''', default='''sam_vit_h_4b8939''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) parser.add_argument( '''--model_hub_id''', default='''ybelkada/segment-anything''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) _lowercase : List[Any] =parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run _lowercase : Optional[Any] =True except (ImportError, AttributeError): _lowercase : Optional[int] =object def A__ ( *lowercase: Optional[int], **lowercase: Any ) -> int: pass _lowercase : List[Any] =False _lowercase : str =logging.get_logger('''transformers-cli/serving''') def A__ ( lowercase: Namespace ) -> Dict: A : str =pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) return ServeCommand(lowercase, args.host, args.port, args.workers ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : dict class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[str] lowercase : Optional[List[int]] class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : str class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Any class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> List[Any]: A : Optional[Any] =parser.add_parser( 'serve' , help='CLI tool to run inference requests through REST and GraphQL endpoints.' ) serve_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , choices=get_supported_tasks() , help='The task to run the pipeline on' , ) serve_parser.add_argument('--host' , type=SCREAMING_SNAKE_CASE__ , default='localhost' , help='Interface the server will listen on.' ) serve_parser.add_argument('--port' , type=SCREAMING_SNAKE_CASE__ , default=88_88 , help='Port the serving will listen to.' ) serve_parser.add_argument('--workers' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of http workers' ) serve_parser.add_argument('--model' , type=SCREAMING_SNAKE_CASE__ , help='Model\'s name or path to stored model.' ) serve_parser.add_argument('--config' , type=SCREAMING_SNAKE_CASE__ , help='Model\'s config name or path to stored model.' ) serve_parser.add_argument('--tokenizer' , type=SCREAMING_SNAKE_CASE__ , help='Tokenizer name to use.' ) serve_parser.add_argument( '--device' , type=SCREAMING_SNAKE_CASE__ , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) serve_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Pipeline , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: A : str =pipeline A : List[Any] =host A : List[str] =port A : str =workers if not _serve_dependencies_installed: raise RuntimeError( 'Using serve command requires FastAPI and uvicorn. ' 'Please install transformers with [serving]: pip install "transformers[serving]".' 'Or install FastAPI and uvicorn separately.' ) else: logger.info(f'Serving model over {host}:{port}' ) A : List[str] =FastAPI( routes=[ APIRoute( '/' , self.model_info , response_model=SCREAMING_SNAKE_CASE__ , response_class=SCREAMING_SNAKE_CASE__ , methods=['GET'] , ), APIRoute( '/tokenize' , self.tokenize , response_model=SCREAMING_SNAKE_CASE__ , response_class=SCREAMING_SNAKE_CASE__ , methods=['POST'] , ), APIRoute( '/detokenize' , self.detokenize , response_model=SCREAMING_SNAKE_CASE__ , response_class=SCREAMING_SNAKE_CASE__ , methods=['POST'] , ), APIRoute( '/forward' , self.forward , response_model=SCREAMING_SNAKE_CASE__ , response_class=SCREAMING_SNAKE_CASE__ , methods=['POST'] , ), ] , timeout=6_00 , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: run(self._app , host=self.host , port=self.port , workers=self.workers ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[str]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str = Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ : bool = Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) ) -> int: try: A : str =self._pipeline.tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) if return_ids: A : Optional[int] =self._pipeline.tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) return ServeTokenizeResult(tokens=SCREAMING_SNAKE_CASE__ , tokens_ids=SCREAMING_SNAKE_CASE__ ) else: return ServeTokenizeResult(tokens=SCREAMING_SNAKE_CASE__ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={'model': '', 'error': str(SCREAMING_SNAKE_CASE__ )} ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] = Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ : bool = Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ : bool = Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) , ) -> str: try: A : List[Any] =self._pipeline.tokenizer.decode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return ServeDeTokenizeResult(model='' , text=SCREAMING_SNAKE_CASE__ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={'model': '', 'error': str(SCREAMING_SNAKE_CASE__ )} ) async def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any]=Body(SCREAMING_SNAKE_CASE__ , embed=SCREAMING_SNAKE_CASE__ ) ) -> List[str]: # Check we don't have empty string if len(SCREAMING_SNAKE_CASE__ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model A : Any =self._pipeline(SCREAMING_SNAKE_CASE__ ) return ServeForwardResult(output=SCREAMING_SNAKE_CASE__ ) except Exception as e: raise HTTPException(5_00 , {'error': str(SCREAMING_SNAKE_CASE__ )} )
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : int=99 , SCREAMING_SNAKE_CASE__ : Tuple=64 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 , SCREAMING_SNAKE_CASE__ : Any=64 , SCREAMING_SNAKE_CASE__ : str="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=5_12 , SCREAMING_SNAKE_CASE__ : int=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : int=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Any: A : Tuple =parent A : int =batch_size A : Any =seq_length A : Union[str, Any] =is_training A : List[str] =use_input_mask A : List[Any] =use_token_type_ids A : Any =use_labels A : Tuple =vocab_size A : List[Any] =hidden_size A : List[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : List[str] =intermediate_size A : Optional[int] =hidden_act A : List[Any] =hidden_dropout_prob A : Optional[int] =attention_probs_dropout_prob A : Any =max_position_embeddings A : str =type_vocab_size A : Tuple =type_sequence_label_size A : Dict =initializer_range A : List[str] =num_labels A : Tuple =num_choices A : Dict =scope def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[str]: return MPNetConfig.from_pretrained('microsoft/mpnet-base' ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[str]: A : Any =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Tuple =None if self.use_input_mask: A : List[Any] =random_attention_mask([self.batch_size, self.seq_length] ) A : str =None A : Optional[int] =None A : Optional[int] =None if self.use_labels: A : Any =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Dict =ids_tensor([self.batch_size] , self.num_choices ) A : Tuple =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : Any ) -> int: return MPNetConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: A : Any =MPNetModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : int =model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[int] =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: A : Optional[Any] =MPNetForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : List[str] =model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_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 SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: A : Optional[Any] =self.num_labels A : Optional[int] =MPNetForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : Optional[Any] =model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: A : Optional[int] =self.num_choices A : Dict =MPNetForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : int =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Dict =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : int =model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Optional[int] =self.num_labels A : Optional[Any] =MPNetForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : Union[str, Any] =model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : List[str] =self.prepare_config_and_inputs() ((A) , (A) , (A) , (A) , (A) , (A)) : str =config_and_inputs A : int ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : int = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) lowercase : Any = ( { "feature-extraction": MPNetModel, "fill-mask": MPNetForMaskedLM, "question-answering": MPNetForQuestionAnswering, "text-classification": MPNetForSequenceClassification, "token-classification": MPNetForTokenClassification, "zero-shot": MPNetForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : List[str] = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> str: A : Dict =MPNetModelTester(self ) A : Union[str, Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: A : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: A : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[int]: A : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> int: A : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: A : List[Any] =MPNetModel.from_pretrained('microsoft/mpnet-base' ) A : Optional[int] =torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) A : List[Any] =model(SCREAMING_SNAKE_CASE__ )[0] A : str =torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =torch.tensor( [[[-0.0_5_5_0, 0.1_9_4_3, -0.0_7_4_0], [-0.0_5_6_2, 0.2_2_1_1, -0.0_5_7_9], [-0.0_4_3_7, 0.3_3_3_7, -0.0_6_4_1]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
661
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
def A__ ( lowercase: list, lowercase: list ) -> float: _validate_point(lowercase ) _validate_point(lowercase ) if len(lowercase ) != len(lowercase ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(a - b ) for a, b in zip(lowercase, lowercase ) ) ) def A__ ( lowercase: list[float] ) -> None: if point: if isinstance(lowercase, lowercase ): for item in point: if not isinstance(lowercase, (int, float) ): A : str =( 'Expected a list of numbers as input, found ' F'{type(lowercase ).__name__}' ) raise TypeError(lowercase ) else: A : Tuple =F'Expected a list of numbers as input, found {type(lowercase ).__name__}' raise TypeError(lowercase ) else: raise ValueError('Missing an input' ) def A__ ( lowercase: list, lowercase: list ) -> float: _validate_point(lowercase ) _validate_point(lowercase ) if len(lowercase ) != len(lowercase ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(x - y ) for x, y in zip(lowercase, lowercase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : int lowercase : float = 0.0 lowercase : int = 1 lowercase : int = 1 lowercase : bool = True lowercase : bool = False lowercase : bool = False lowercase : bool = False lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: A : Tuple =[] A : Union[str, Any] =[] for i in range(self.num_layers ): A : Union[str, Any] =self.in_channels if i == 0 else self.out_channels A : int =FlaxResnetBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =resnets A : Any =attentions if self.add_downsample: A : int =FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple=True ) -> int: A : List[Any] =() for resnet, attn in zip(self.resnets , self.attentions ): A : Dict =resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) A : Any =attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) if self.add_downsample: A : Any =self.downsamplers_a(SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) return hidden_states, output_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : int lowercase : float = 0.0 lowercase : int = 1 lowercase : bool = True lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =[] for i in range(self.num_layers ): A : Dict =self.in_channels if i == 0 else self.out_channels A : Tuple =FlaxResnetBlockaD( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) A : Dict =resnets if self.add_downsample: A : Optional[Any] =FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int=True ) -> str: A : int =() for resnet in self.resnets: A : List[str] =resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) if self.add_downsample: A : Dict =self.downsamplers_a(SCREAMING_SNAKE_CASE__ ) output_states += (hidden_states,) return hidden_states, output_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : int lowercase : int lowercase : float = 0.0 lowercase : int = 1 lowercase : int = 1 lowercase : bool = True lowercase : bool = False lowercase : bool = False lowercase : bool = False lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: A : Union[str, Any] =[] A : List[str] =[] for i in range(self.num_layers ): A : Any =self.in_channels if (i == self.num_layers - 1) else self.out_channels A : List[Any] =self.prev_output_channel if i == 0 else self.out_channels A : List[str] =FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) A : Any =FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) A : Tuple =resnets A : Union[str, Any] =attentions if self.add_upsample: A : List[str] =FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str=True ) -> Union[str, Any]: for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states A : Dict =res_hidden_states_tuple[-1] A : Dict =res_hidden_states_tuple[:-1] A : Any =jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) A : Optional[Any] =resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) if self.add_upsample: A : Optional[int] =self.upsamplers_a(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : int lowercase : int lowercase : float = 0.0 lowercase : int = 1 lowercase : bool = True lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : int =[] for i in range(self.num_layers ): A : List[str] =self.in_channels if (i == self.num_layers - 1) else self.out_channels A : int =self.prev_output_channel if i == 0 else self.out_channels A : Optional[Any] =FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =resnets if self.add_upsample: A : Any =FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any]=True ) -> List[Any]: for resnet in self.resnets: # pop res hidden states A : Union[str, Any] =res_hidden_states_tuple[-1] A : Union[str, Any] =res_hidden_states_tuple[:-1] A : List[str] =jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) A : Tuple =resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) if self.add_upsample: A : Union[str, Any] =self.upsamplers_a(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : float = 0.0 lowercase : int = 1 lowercase : int = 1 lowercase : bool = False lowercase : bool = False lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: # there is always at least one resnet A : Optional[int] =[ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] A : Optional[Any] =[] for _ in range(self.num_layers ): A : int =FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(SCREAMING_SNAKE_CASE__ ) A : int =FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(SCREAMING_SNAKE_CASE__ ) A : Tuple =resnets A : Optional[int] =attentions def __call__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ) -> Optional[int]: A : Optional[Any] =self.resnets[0](SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): A : Union[str, Any] =attn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) A : Any =resnet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , deterministic=SCREAMING_SNAKE_CASE__ ) return hidden_states
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = ["image_processor", "tokenizer"] lowercase : Optional[Any] = "BlipImageProcessor" lowercase : int = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: A : Optional[Any] =False super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Tuple =self.image_processor def __call__( self : List[Any] , SCREAMING_SNAKE_CASE__ : ImageInput = None , SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: A : Optional[int] =self.tokenizer A : Union[str, Any] =self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) return text_encoding # add pixel_values A : int =self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) if text is not None: A : Union[str, Any] =self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) else: A : str =None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__ ) return encoding_image_processor def SCREAMING_SNAKE_CASE_ ( self : int , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: A : Dict =self.tokenizer.model_input_names A : Optional[int] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _lowercase : Tuple ={'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowercase : List[str] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowercase : Optional[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str ) -> int: A : Any =ZeroShotClassificationPipeline( model=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , candidate_labels=['polics', 'health'] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: A : str =classifier('Who are you voting for in 2020?' , candidate_labels='politics' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ )]} ) # No kwarg A : List[Any] =classifier('Who are you voting for in 2020?' , ['politics'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ )]} ) A : Optional[int] =classifier('Who are you voting for in 2020?' , candidate_labels=['politics'] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ )]} ) A : Optional[int] =classifier('Who are you voting for in 2020?' , candidate_labels='politics, public health' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) A : Dict =classifier('Who are you voting for in 2020?' , candidate_labels=['politics', 'public health'] ) self.assertEqual( SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) A : int =classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='This text is about {}' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ )]} ) # https://github.com/huggingface/transformers/issues/13846 A : List[str] =classifier(['I am happy'] , ['positive', 'negative'] ) self.assertEqual( SCREAMING_SNAKE_CASE__ , [ {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )]} for i in range(1 ) ] , ) A : Optional[int] =classifier(['I am happy', 'I am sad'] , ['positive', 'negative'] ) self.assertEqual( SCREAMING_SNAKE_CASE__ , [ {'sequence': ANY(SCREAMING_SNAKE_CASE__ ), 'labels': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )], 'scores': [ANY(SCREAMING_SNAKE_CASE__ ), ANY(SCREAMING_SNAKE_CASE__ )]} for i in range(2 ) ] , ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier('' , candidate_labels='politics' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier(SCREAMING_SNAKE_CASE__ , candidate_labels='politics' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier('Who are you voting for in 2020?' , candidate_labels='' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier('Who are you voting for in 2020?' , candidate_labels=SCREAMING_SNAKE_CASE__ ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='Not formatting template' , ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template=SCREAMING_SNAKE_CASE__ , ) self.run_entailment_id(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Pipeline ) -> Dict: A : Any =zero_shot_classifier.model.config A : Any =config.labelaid A : Optional[int] =zero_shot_classifier.entailment_id A : List[str] ={'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) A : Optional[int] ={'entailment': 0, 'neutral': 1, 'contradiction': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) A : Tuple ={'ENTAIL': 0, 'NON-ENTAIL': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) A : List[str] ={'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) A : Dict =original_labelaid self.assertEqual(SCREAMING_SNAKE_CASE__ , zero_shot_classifier.entailment_id ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: A : Tuple =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( 'Who are you voting for in 2020?' * 1_00 , candidate_labels=['politics', 'public health', 'science'] ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: A : List[str] =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) A : str =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : List[Any] =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='tf' , ) A : Tuple =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @slow @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: A : Union[str, Any] =pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='pt' ) A : Union[str, Any] =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) A : List[Any] =zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=SCREAMING_SNAKE_CASE__ , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , ) @slow @require_tf def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: A : Tuple =pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='tf' ) A : Optional[int] =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) A : List[Any] =zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=SCREAMING_SNAKE_CASE__ , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , )
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor _lowercase : int =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[str] ) -> None: warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
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 SCREAMING_SNAKE_CASE_ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ) -> str: pass @is_pipeline_test @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : str = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: A : int =pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) A : List[Any] =[ { '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 : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: A : Any =vqa_pipeline(SCREAMING_SNAKE_CASE__ , top_k=1 ) self.assertEqual( SCREAMING_SNAKE_CASE__ , [ [{'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}], [{'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}], ] , ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[Any]: A : Any =pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) A : str ='./tests/fixtures/tests_samples/COCO/000000039769.png' A : Dict ='How many cats are there?' A : Optional[Any] =vqa_pipeline(image=SCREAMING_SNAKE_CASE__ , question='How many cats are there?' , top_k=2 ) self.assertEqual( SCREAMING_SNAKE_CASE__ , [{'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}, {'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}] ) A : List[Any] =vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( SCREAMING_SNAKE_CASE__ , [{'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}, {'score': ANY(SCREAMING_SNAKE_CASE__ ), 'answer': ANY(SCREAMING_SNAKE_CASE__ )}] ) @slow @require_torch def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Union[str, Any] =pipeline('visual-question-answering' , model='dandelin/vilt-b32-finetuned-vqa' ) A : int ='./tests/fixtures/tests_samples/COCO/000000039769.png' A : int ='How many cats are there?' A : List[Any] =vqa_pipeline(image=SCREAMING_SNAKE_CASE__ , question=SCREAMING_SNAKE_CASE__ , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4 ) , [{'score': 0.8_7_9_9, 'answer': '2'}, {'score': 0.2_9_6, 'answer': '1'}] ) A : Optional[int] =vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4 ) , [{'score': 0.8_7_9_9, 'answer': '2'}, {'score': 0.2_9_6, 'answer': '1'}] ) A : str =vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4 ) , [[{'score': 0.8_7_9_9, 'answer': '2'}, {'score': 0.2_9_6, 'answer': '1'}]] * 2 , ) @require_tf @unittest.skip('Visual question answering not implemented in TF' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[Any]: pass
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowercase : Tuple =logging.get_logger(__name__) def A__ ( lowercase: str, lowercase: str, lowercase: Any ) -> Any: return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def A__ ( lowercase: np.ndarray, lowercase: Optional[str], lowercase: Optional[str] = None ) -> Tuple: A : Union[str, Any] =tesseract_config if tesseract_config is not None else '' # apply OCR A : List[Any] =to_pil_image(lowercase ) A , A : Optional[Any] =pil_image.size A : List[Any] =pytesseract.image_to_data(lowercase, lang=lowercase, output_type='dict', config=lowercase ) A , A , A , A , A : List[Any] =data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates A : List[Any] =[idx for idx, word in enumerate(lowercase ) if not word.strip()] A : Dict =[word for idx, word in enumerate(lowercase ) if idx not in irrelevant_indices] A : Tuple =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] A : Optional[int] =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] A : List[str] =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] A : Tuple =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format A : Dict =[] for x, y, w, h in zip(lowercase, lowercase, lowercase, lowercase ): A : Any =[x, y, x + w, y + h] actual_boxes.append(lowercase ) # finally, normalize the bounding boxes A : Dict =[] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase, lowercase, lowercase ) ) assert len(lowercase ) == len(lowercase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[str] = ["pixel_values"] def __init__( self : Any , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = "" , **SCREAMING_SNAKE_CASE__ : int , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =size if size is not None else {'height': 2_24, 'width': 2_24} A : Optional[int] =get_size_dict(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =do_resize A : Union[str, Any] =size A : Any =resample A : Optional[int] =apply_ocr A : int =ocr_lang A : List[Any] =tesseract_config def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> np.ndarray: A : Dict =get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) A : Union[str, Any] =(size['height'], size['width']) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> PIL.Image.Image: A : str =do_resize if do_resize is not None else self.do_resize A : Optional[int] =size if size is not None else self.size A : Dict =get_size_dict(SCREAMING_SNAKE_CASE__ ) A : Any =resample if resample is not None else self.resample A : int =apply_ocr if apply_ocr is not None else self.apply_ocr A : int =ocr_lang if ocr_lang is not None else self.ocr_lang A : Dict =tesseract_config if tesseract_config is not None else self.tesseract_config A : Optional[Any] =make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) # All transformations expect numpy arrays. A : Union[str, Any] =[to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if apply_ocr: requires_backends(self , 'pytesseract' ) A : Dict =[] A : Any =[] for image in images: A , A : Dict =apply_tesseract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) words_batch.append(SCREAMING_SNAKE_CASE__ ) boxes_batch.append(SCREAMING_SNAKE_CASE__ ) if do_resize: A : List[Any] =[self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) A : Tuple =[flip_channel_order(SCREAMING_SNAKE_CASE__ ) for image in images] A : List[str] =[to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] A : Optional[int] =BatchFeature(data={'pixel_values': images} , tensor_type=SCREAMING_SNAKE_CASE__ ) if apply_ocr: A : Dict =words_batch A : List[str] =boxes_batch return data
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
def A__ ( lowercase: Optional[Any] ) -> Dict: A : Tuple =[0] * len(lowercase ) A : Optional[int] =[] A : int =[] A : Tuple =0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowercase ) ): if indegree[i] == 0: queue.append(lowercase ) while queue: A : Optional[Any] =queue.pop(0 ) cnt += 1 topo.append(lowercase ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(lowercase ) if cnt != len(lowercase ): print('Cycle exists' ) else: print(lowercase ) # Adjacency List of Graph _lowercase : List[Any] ={0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : List[Any] =logging.get_logger(__name__) _lowercase : Optional[Any] ={ '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : str = "dpr" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=3_05_22 , SCREAMING_SNAKE_CASE__ : Tuple=7_68 , SCREAMING_SNAKE_CASE__ : List[Any]=12 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Any=30_72 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : str=0.0_2 , SCREAMING_SNAKE_CASE__ : Dict=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : List[Any]="absolute" , SCREAMING_SNAKE_CASE__ : int = 0 , **SCREAMING_SNAKE_CASE__ : int , ) -> Optional[Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Tuple =vocab_size A : Tuple =hidden_size A : str =num_hidden_layers A : Any =num_attention_heads A : Optional[int] =hidden_act A : str =intermediate_size A : List[str] =hidden_dropout_prob A : List[Any] =attention_probs_dropout_prob A : Optional[int] =max_position_embeddings A : Tuple =type_vocab_size A : int =initializer_range A : Dict =layer_norm_eps A : Any =projection_dim A : Optional[Any] =position_embedding_type
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params _lowercase : int =getLogger(__name__) _lowercase : Dict ='''cuda''' if torch.cuda.is_available() else '''cpu''' def A__ ( lowercase: List[str], lowercase: str, lowercase: str, lowercase: int = 8, lowercase: str = DEFAULT_DEVICE, lowercase: Optional[Any]=False, lowercase: Union[str, Any]="summarization", lowercase: Any=None, **lowercase: str, ) -> Dict: A : List[Any] =Path(lowercase ).open('w', encoding='utf-8' ) A : int =str(lowercase ) A : Optional[Any] =AutoModelForSeqaSeqLM.from_pretrained(lowercase ).to(lowercase ) if fpaa: A : List[str] =model.half() A : Dict =AutoTokenizer.from_pretrained(lowercase ) logger.info(F'Inferred tokenizer type: {tokenizer.__class__}' ) # if this is wrong, check config.model_type. A : Any =time.time() # update config with task specific params use_task_specific_params(lowercase, lowercase ) if prefix is None: A : int =prefix or getattr(model.config, 'prefix', '' ) or '' for examples_chunk in tqdm(list(chunks(lowercase, lowercase ) ) ): A : Dict =[prefix + text for text in examples_chunk] A : List[str] =tokenizer(lowercase, return_tensors='pt', truncation=lowercase, padding='longest' ).to(lowercase ) A : List[Any] =model.generate( input_ids=batch.input_ids, attention_mask=batch.attention_mask, **lowercase, ) A : Optional[int] =tokenizer.batch_decode(lowercase, skip_special_tokens=lowercase, clean_up_tokenization_spaces=lowercase ) for hypothesis in dec: fout.write(hypothesis + '\n' ) fout.flush() fout.close() A : Dict =int(time.time() - start_time ) # seconds A : List[Any] =len(lowercase ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs, 4 )} def A__ ( ) -> List[Any]: return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' ) def A__ ( lowercase: Union[str, Any]=True ) -> Any: A : Union[str, Any] =argparse.ArgumentParser() parser.add_argument('model_name', type=lowercase, help='like facebook/bart-large-cnn,t5-base, etc.' ) parser.add_argument('input_path', type=lowercase, help='like cnn_dm/test.source' ) parser.add_argument('save_path', type=lowercase, help='where to save summaries' ) parser.add_argument('--reference_path', type=lowercase, required=lowercase, help='like cnn_dm/test.target' ) parser.add_argument('--score_path', type=lowercase, required=lowercase, default='metrics.json', help='where to save metrics' ) parser.add_argument('--device', type=lowercase, required=lowercase, default=lowercase, help='cuda, cuda:1, cpu etc.' ) parser.add_argument( '--prefix', type=lowercase, required=lowercase, default=lowercase, help='will be added to the begininng of src examples' ) parser.add_argument('--task', type=lowercase, default='summarization', help='used for task_specific_params + metrics' ) parser.add_argument('--bs', type=lowercase, default=8, required=lowercase, help='batch size' ) parser.add_argument( '--n_obs', type=lowercase, default=-1, required=lowercase, help='How many observations. Defaults to all.' ) parser.add_argument('--fp16', action='store_true' ) parser.add_argument('--dump-args', action='store_true', help='print the custom hparams with the results' ) parser.add_argument( '--info', nargs='?', type=lowercase, const=datetime_now(), help=( 'use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.' ' lang=en-ru. If no value is passed, the current datetime string will be used.' ), ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate A , A : str =parser.parse_known_args() A : Optional[int] =parse_numeric_n_bool_cl_kwargs(lowercase ) if parsed_args and verbose: print(F'parsed the following generate kwargs: {parsed_args}' ) A : Optional[int] =[' ' + x.rstrip() if 't5' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: A : List[str] =examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=lowercase ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F'score_path {args.score_path} will be overwritten unless you type ctrl-c.' ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('Can\'t mix --fp16 and --device cpu' ) A : Tuple =generate_summaries_or_translations( lowercase, args.save_path, args.model_name, batch_size=args.bs, device=args.device, fpaa=args.fpaa, task=args.task, prefix=args.prefix, **lowercase, ) if args.reference_path is None: return {} # Compute scores A : Tuple =calculate_bleu if 'translation' in args.task else calculate_rouge A : Tuple =[x.rstrip() for x in open(args.save_path ).readlines()] A : Any =[x.rstrip() for x in open(args.reference_path ).readlines()][: len(lowercase )] A : dict =score_fn(lowercase, lowercase ) scores.update(lowercase ) if args.dump_args: scores.update(lowercase ) if args.info: A : Tuple =args.info if verbose: print(lowercase ) if args.score_path is not None: json.dump(lowercase, open(args.score_path, 'w' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
from __future__ import annotations from collections.abc import MutableSequence class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : MutableSequence[float] ) -> None: if len(SCREAMING_SNAKE_CASE__ ) != degree + 1: raise ValueError( 'The number of coefficients should be equal to the degree + 1.' ) A : list[float] =list(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =degree def __add__( self : Dict , SCREAMING_SNAKE_CASE__ : Polynomial ) -> Polynomial: if self.degree > polynomial_a.degree: A : Any =self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , SCREAMING_SNAKE_CASE__ ) else: A : str =polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , SCREAMING_SNAKE_CASE__ ) def __sub__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Polynomial ) -> Polynomial: return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self : Optional[int] ) -> Polynomial: return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Polynomial ) -> Polynomial: A : list[float] =[0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : int | float ) -> int | float: A : int | float =0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Tuple ) -> str: A : Tuple ='' for i in range(self.degree , -1 , -1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(SCREAMING_SNAKE_CASE__ ) return polynomial def __repr__( self : Union[str, Any] ) -> str: return self.__str__() def SCREAMING_SNAKE_CASE_ ( self : str ) -> Polynomial: A : list[float] =[0] * self.degree for i in range(self.degree ): A : List[Any] =self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : int | float = 0 ) -> Polynomial: A : list[float] =[0] * (self.degree + 2) A : List[Any] =constant for i in range(self.degree + 1 ): A : Dict =self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , SCREAMING_SNAKE_CASE__ ) def __eq__( self : int , SCREAMING_SNAKE_CASE__ : object ) -> bool: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : str , SCREAMING_SNAKE_CASE__ : object ) -> bool: return not self.__eq__(SCREAMING_SNAKE_CASE__ )
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : List[Any] =logging.get_logger(__name__) _lowercase : Optional[Any] ={ '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[str] = "vivit" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2_24 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=32 , SCREAMING_SNAKE_CASE__ : str=[2, 16, 16] , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=7_68 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : int=30_72 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu_fast" , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : Dict=1e-06 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: A : str =hidden_size A : str =num_hidden_layers A : int =num_attention_heads A : List[str] =intermediate_size A : int =hidden_act A : Tuple =hidden_dropout_prob A : Optional[int] =attention_probs_dropout_prob A : Any =initializer_range A : Any =layer_norm_eps A : str =image_size A : Tuple =num_frames A : List[str] =tubelet_size A : Any =num_channels A : Optional[Any] =qkv_bias super().__init__(**SCREAMING_SNAKE_CASE__ )
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, 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=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict=13 , SCREAMING_SNAKE_CASE__ : Any=7 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=99 , SCREAMING_SNAKE_CASE__ : List[Any]=32 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=37 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Any=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : str=4 , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> List[Any]: A : List[str] =parent A : Optional[Any] =13 A : List[str] =7 A : Optional[int] =True A : Union[str, Any] =True A : Optional[int] =True A : Tuple =True A : List[str] =99 A : Optional[int] =32 A : Any =2 A : str =4 A : List[Any] =37 A : Union[str, Any] ='gelu' A : Tuple =0.1 A : Optional[Any] =0.1 A : Any =5_12 A : Tuple =16 A : Any =2 A : List[Any] =0.0_2 A : str =3 A : Optional[int] =4 A : Dict =None def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[str]: A : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] =None if self.use_input_mask: A : Union[str, Any] =random_attention_mask([self.batch_size, self.seq_length] ) A : Optional[int] =None if self.use_token_type_ids: A : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : str =None A : Any =None A : List[Any] =None if self.use_labels: A : int =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Optional[int] =ids_tensor([self.batch_size] , self.num_choices ) A : Optional[int] =RoFormerConfig( 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 , return_dict=SCREAMING_SNAKE_CASE__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : str =TFRoFormerModel(config=SCREAMING_SNAKE_CASE__ ) A : List[Any] ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} A : int =[input_ids, input_mask] A : Tuple =model(SCREAMING_SNAKE_CASE__ ) A : Dict =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: A : int =True A : int =TFRoFormerForCausalLM(config=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A : str =model(SCREAMING_SNAKE_CASE__ )['logits'] self.parent.assertListEqual( list(prediction_scores.numpy().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__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Union[str, Any]: A : Any =TFRoFormerForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) A : int ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A : Optional[Any] =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: A : str =self.num_labels A : str =TFRoFormerForSequenceClassification(config=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A : Any =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: A : str =self.num_choices A : Dict =TFRoFormerForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) A : List[str] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) A : Optional[int] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) A : Optional[int] ={ 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } A : int =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: A : List[Any] =self.num_labels A : Optional[int] =TFRoFormerForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A : Optional[int] =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: A : Tuple =TFRoFormerForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) A : Dict ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A : Any =model(SCREAMING_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 SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : List[str] =self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) : List[str] =config_and_inputs A : Union[str, Any] ={'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''' lowercase : str = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) lowercase : List[Any] = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) lowercase : List[Any] = False lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Any =TFRoFormerModelTester(self ) A : int =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> int: A : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: A : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Tuple: A : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: A : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[Any]: A : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Any: A : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: A : Optional[Any] =TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: A : Dict =TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) A : Any =tf.constant([[0, 1, 2, 3, 4, 5]] ) A : str =model(SCREAMING_SNAKE_CASE__ )[0] # TODO Replace vocab size A : List[str] =5_00_00 A : Dict =[1, 6, vocab_size] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. A : Optional[int] =tf.constant( [ [ [-0.1_2_0_5_3_3_4_1, -1.0_2_6_4_9_0_1, 0.2_9_2_2_1_9_4_6], [-1.5_1_3_3_7_8_3, 0.1_9_7_4_3_3, 0.1_5_1_9_0_6_0_7], [-5.0_1_3_5_4_0_3, -3.9_0_0_2_5_6, -0.8_4_0_3_8_7_6_4], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : Optional[Any] = 1e-4 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: A : Dict =tf.constant([[4, 10]] ) A : str =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) A : Dict =emba(input_ids.shape ) A : Optional[Any] =tf.constant( [[0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 1.0_0_0_0, 1.0_0_0_0, 1.0_0_0_0], [0.8_4_1_5, 0.0_4_6_4, 0.0_0_2_2, 0.5_4_0_3, 0.9_9_8_9, 1.0_0_0_0]] ) tf.debugging.assert_near(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=self.tolerance ) def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[Any]: A : Tuple =tf.constant( [ [0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0], [0.8_4_1_5, 0.8_2_1_9, 0.8_0_2_0, 0.7_8_1_9, 0.7_6_1_7], [0.9_0_9_3, 0.9_3_6_4, 0.9_5_8_1, 0.9_7_4_9, 0.9_8_7_0], ] ) A : List[str] =TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_12 , embedding_dim=5_12 ) emba([2, 16, 5_12] ) A : str =emba.weight[:3, :5] tf.debugging.assert_near(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=self.tolerance ) @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : List[str] = 1e-4 def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # 2,12,16,64 A : List[Any] =tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 1_00 A : Dict =-tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 1_00 A : List[str] =TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) A : Any =embed_positions([2, 16, 7_68] )[None, None, :, :] A , A : Dict =TFRoFormerSelfAttention.apply_rotary_position_embeddings( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tf.constant( [ [0.0_0_0_0, 0.0_1_0_0, 0.0_2_0_0, 0.0_3_0_0, 0.0_4_0_0, 0.0_5_0_0, 0.0_6_0_0, 0.0_7_0_0], [-0.2_0_1_2, 0.8_8_9_7, 0.0_2_6_3, 0.9_4_0_1, 0.2_0_7_4, 0.9_4_6_3, 0.3_4_8_1, 0.9_3_4_3], [-1.7_0_5_7, 0.6_2_7_1, -1.2_1_4_5, 1.3_8_9_7, -0.6_3_0_3, 1.7_6_4_7, -0.1_1_7_3, 1.8_9_8_5], [-2.1_7_3_1, -1.6_3_9_7, -2.7_3_5_8, 0.2_8_5_4, -2.1_8_4_0, 1.7_1_8_3, -1.3_0_1_8, 2.4_8_7_1], [0.2_7_1_7, -3.6_1_7_3, -2.9_2_0_6, -2.1_9_8_8, -3.6_6_3_8, 0.3_8_5_8, -2.9_1_5_5, 2.2_9_8_0], [3.9_8_5_9, -2.1_5_8_0, -0.7_9_8_4, -4.4_9_0_4, -4.1_1_8_1, -2.0_2_5_2, -4.4_7_8_2, 1.1_2_5_3], ] ) A : Union[str, Any] =tf.constant( [ [0.0_0_0_0, -0.0_1_0_0, -0.0_2_0_0, -0.0_3_0_0, -0.0_4_0_0, -0.0_5_0_0, -0.0_6_0_0, -0.0_7_0_0], [0.2_0_1_2, -0.8_8_9_7, -0.0_2_6_3, -0.9_4_0_1, -0.2_0_7_4, -0.9_4_6_3, -0.3_4_8_1, -0.9_3_4_3], [1.7_0_5_7, -0.6_2_7_1, 1.2_1_4_5, -1.3_8_9_7, 0.6_3_0_3, -1.7_6_4_7, 0.1_1_7_3, -1.8_9_8_5], [2.1_7_3_1, 1.6_3_9_7, 2.7_3_5_8, -0.2_8_5_4, 2.1_8_4_0, -1.7_1_8_3, 1.3_0_1_8, -2.4_8_7_1], [-0.2_7_1_7, 3.6_1_7_3, 2.9_2_0_6, 2.1_9_8_8, 3.6_6_3_8, -0.3_8_5_8, 2.9_1_5_5, -2.2_9_8_0], [-3.9_8_5_9, 2.1_5_8_0, 0.7_9_8_4, 4.4_9_0_4, 4.1_1_8_1, 2.0_2_5_2, 4.4_7_8_2, -1.1_2_5_3], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE__ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE__ , atol=self.tolerance )
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A : Optional[int] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : str =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : Optional[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A : Tuple ='base imports' if key == 'none' else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\n'.join(F'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
661
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
_lowercase : List[str] ={str(digit): digit**5 for digit in range(1_0)} def A__ ( lowercase: int ) -> int: return sum(DIGITS_FIFTH_POWER[digit] for digit in str(lowercase ) ) def A__ ( ) -> int: return sum( number for number in range(1_000, 1_000_000 ) if number == digits_fifth_powers_sum(lowercase ) ) if __name__ == "__main__": print(solution())
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> str: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
from __future__ import annotations _lowercase : Tuple =[] def A__ ( lowercase: list[list[int]], lowercase: int, lowercase: int ) -> bool: for i in range(len(lowercase ) ): if board[row][i] == 1: return False for i in range(len(lowercase ) ): if board[i][column] == 1: return False for i, j in zip(range(lowercase, -1, -1 ), range(lowercase, -1, -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(lowercase, -1, -1 ), range(lowercase, len(lowercase ) ) ): if board[i][j] == 1: return False return True def A__ ( lowercase: list[list[int]], lowercase: int ) -> bool: if row >= len(lowercase ): solution.append(lowercase ) printboard(lowercase ) print() return True for i in range(len(lowercase ) ): if is_safe(lowercase, lowercase, lowercase ): A : int =1 solve(lowercase, row + 1 ) A : List[Any] =0 return False def A__ ( lowercase: list[list[int]] ) -> None: for i in range(len(lowercase ) ): for j in range(len(lowercase ) ): if board[i][j] == 1: print('Q', end=' ' ) else: print('.', end=' ' ) print() # n=int(input("The no. of queens")) _lowercase : Dict =8 _lowercase : Optional[Any] =[[0 for i in range(n)] for j in range(n)] solve(board, 0) print('''The total no. of solutions are :''', len(solution))
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
def A__ ( lowercase: int, lowercase: int ) -> int: A : Any =1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): A : List[Any] =n - k # Calculate C(n,k) for i in range(lowercase ): result *= n - i result //= i + 1 return result def A__ ( lowercase: int ) -> int: return binomial_coefficient(2 * node_count, lowercase ) // (node_count + 1) def A__ ( lowercase: int ) -> int: if n < 0: raise ValueError('factorial() not defined for negative values' ) A : Union[str, Any] =1 for i in range(1, n + 1 ): result *= i return result def A__ ( lowercase: int ) -> int: return catalan_number(lowercase ) * factorial(lowercase ) if __name__ == "__main__": _lowercase : List[Any] =int(input('''Enter the number of nodes: ''').strip() or 0) if node_count <= 0: raise ValueError('''We need some nodes to work with.''') print( f'''Given {node_count} nodes, there are {binary_tree_count(node_count)} ''' f'''binary trees and {catalan_number(node_count)} binary search trees.''' )
661
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 ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Tuple =logging.get_logger(__name__) _lowercase : Any ={ '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "blip_text_model" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=3_05_24 , SCREAMING_SNAKE_CASE__ : List[Any]=7_68 , SCREAMING_SNAKE_CASE__ : List[str]=7_68 , SCREAMING_SNAKE_CASE__ : Any=30_72 , SCREAMING_SNAKE_CASE__ : int=7_68 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_12 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=1e-12 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : str=0.0_2 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_05_22 , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_02 , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Any=True , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , sep_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) A : Dict =vocab_size A : List[str] =hidden_size A : str =encoder_hidden_size A : int =intermediate_size A : Optional[int] =projection_dim A : Optional[int] =hidden_dropout_prob A : Union[str, Any] =num_hidden_layers A : int =num_attention_heads A : Union[str, Any] =max_position_embeddings A : Any =layer_norm_eps A : List[Any] =hidden_act A : List[Any] =initializer_range A : List[Any] =attention_probs_dropout_prob A : str =is_decoder A : str =use_cache @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Any , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) A , A : List[Any] =cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the text config dict if we are loading from BlipConfig if config_dict.get('model_type' ) == "blip": A : List[str] =config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Union[str, Any] = "blip_vision_model" def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[str]=7_68 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_72 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : Dict=3_84 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Tuple="gelu" , SCREAMING_SNAKE_CASE__ : Dict=1e-5 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE__ : Any=1e-10 , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =intermediate_size A : Union[str, Any] =projection_dim A : List[Any] =num_hidden_layers A : List[Any] =num_attention_heads A : Tuple =patch_size A : List[Any] =image_size A : Optional[Any] =initializer_range A : Optional[Any] =attention_dropout A : List[Any] =layer_norm_eps A : int =hidden_act @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : str ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) A , A : List[Any] =cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from BlipConfig if config_dict.get('model_type' ) == "blip": A : Optional[Any] =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = "blip" lowercase : List[Any] = True def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Tuple=5_12 , SCREAMING_SNAKE_CASE__ : Optional[int]=2.6_5_9_2 , SCREAMING_SNAKE_CASE__ : Tuple=2_56 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE__ ) if text_config is None: A : Union[str, Any] ={} logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.' ) if vision_config is None: A : Any ={} logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.' ) A : List[Any] =BlipTextConfig(**SCREAMING_SNAKE_CASE__ ) A : Dict =BlipVisionConfig(**SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =self.vision_config.hidden_size A : Dict =projection_dim A : List[str] =logit_scale_init_value A : int =1.0 A : List[Any] =0.0_2 A : List[str] =image_text_hidden_size @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[Any] , SCREAMING_SNAKE_CASE__ : BlipTextConfig , SCREAMING_SNAKE_CASE__ : BlipVisionConfig , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: A : List[Any] =copy.deepcopy(self.__dict__ ) A : Any =self.text_config.to_dict() A : int =self.vision_config.to_dict() A : str =self.__class__.model_type return output
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' pass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> None: A : Any =data A : Node | None =None def __iter__( self : Dict ) -> Tuple: A : Optional[Any] =self A : str =[] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE__ ) yield node.data A : Optional[int] =node.next_node @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> bool: try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowercase : List[str] =Node(1) _lowercase : Any =Node(2) _lowercase : List[Any] =Node(3) _lowercase : List[Any] =Node(4) print(root_node.has_loop) # False _lowercase : str =root_node.next_node print(root_node.has_loop) # True _lowercase : Optional[Any] =Node(5) _lowercase : Dict =Node(6) _lowercase : List[str] =Node(5) _lowercase : List[Any] =Node(6) print(root_node.has_loop) # False _lowercase : Tuple =Node(1) print(root_node.has_loop) # False
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('socket.socket' ) @patch('builtins.open' ) def A__ ( lowercase: List[Any], lowercase: str ) -> Dict: # ===== initialization ===== A : Optional[Any] =Mock() A : List[str] =conn, Mock() A : Any =iter([1, None] ) A : Dict =lambda lowercase : next(lowercase ) # ===== invoke ===== send_file(filename='mytext.txt', testing=lowercase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets _lowercase : Any =''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' _lowercase : List[Any] ='''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' _lowercase : str =''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def A__ ( lowercase: Dict ) -> List[str]: def remove_articles(lowercase: Optional[int] ): A : List[Any] =re.compile(r'\b(a|an|the)\b', re.UNICODE ) return re.sub(lowercase, ' ', lowercase ) def white_space_fix(lowercase: Optional[Any] ): return " ".join(text.split() ) def remove_punc(lowercase: Dict ): A : Optional[Any] =set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase: Union[str, Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase ) ) ) ) def A__ ( lowercase: Union[str, Any], lowercase: List[Any] ) -> int: return int(normalize_answer(lowercase ) == normalize_answer(lowercase ) ) def A__ ( lowercase: int, lowercase: List[Any] ) -> Any: A : str =[any(compute_exact(lowercase, lowercase ) for ref in refs ) for pred, refs in zip(lowercase, lowercase )] return (sum(lowercase ) / len(lowercase )) * 100 def A__ ( lowercase: Tuple, lowercase: str, lowercase: Union[str, Any], lowercase: List[Any] ) -> List[str]: A : List[Any] =[rgram for rgrams in rgramslist for rgram in rgrams] A : Optional[Any] =Counter(lowercase ) A : Any =Counter(lowercase ) A : int =Counter() for sgram, scount in sgramcounter.items(): A : str =scount * numref A : List[Any] =Counter(lowercase ) A : Optional[int] =Counter() for cgram, ccount in cgramcounter.items(): A : Dict =ccount * numref # KEEP A : int =sgramcounter_rep & cgramcounter_rep A : str =keepgramcounter_rep & rgramcounter A : Union[str, Any] =sgramcounter_rep & rgramcounter A : str =0 A : Optional[int] =0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. A : Union[str, Any] =1 A : List[Any] =1 if len(lowercase ) > 0: A : Optional[Any] =keeptmpscorea / len(lowercase ) if len(lowercase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) A : Dict =keeptmpscorea / sum(keepgramcounterall_rep.values() ) A : Dict =0 if keepscore_precision > 0 or keepscore_recall > 0: A : Union[str, Any] =2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION A : Optional[int] =sgramcounter_rep - cgramcounter_rep A : Union[str, Any] =delgramcounter_rep - rgramcounter A : Tuple =sgramcounter_rep - rgramcounter A : int =0 A : Optional[Any] =0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. A : List[str] =1 if len(lowercase ) > 0: A : List[Any] =deltmpscorea / len(lowercase ) # ADDITION A : List[Any] =set(lowercase ) - set(lowercase ) A : Optional[Any] =set(lowercase ) & set(lowercase ) A : int =set(lowercase ) - set(lowercase ) A : int =0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. A : List[Any] =1 A : int =1 if len(lowercase ) > 0: A : Optional[Any] =addtmpscore / len(lowercase ) if len(lowercase ) > 0: A : List[Any] =addtmpscore / len(lowercase ) A : int =0 if addscore_precision > 0 or addscore_recall > 0: A : Dict =2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A__ ( lowercase: Optional[Any], lowercase: str, lowercase: Optional[Any] ) -> Any: A : int =len(lowercase ) A : Dict =ssent.split(' ' ) A : str =csent.split(' ' ) A : int =[] A : Any =[] A : List[Any] =[] A : Any =[] A : List[Any] =[] A : Optional[int] =[] A : Tuple =[] A : List[str] =[] A : List[Any] =[] A : Any =[] for rsent in rsents: A : Any =rsent.split(' ' ) A : List[str] =[] A : Dict =[] A : Dict =[] ragramslist.append(lowercase ) for i in range(0, len(lowercase ) - 1 ): if i < len(lowercase ) - 1: A : List[Any] =ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(lowercase ) if i < len(lowercase ) - 2: A : Dict =ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(lowercase ) if i < len(lowercase ) - 3: A : Optional[Any] =ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(lowercase ) ragramslist.append(lowercase ) ragramslist.append(lowercase ) ragramslist.append(lowercase ) for i in range(0, len(lowercase ) - 1 ): if i < len(lowercase ) - 1: A : Tuple =sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(lowercase ) if i < len(lowercase ) - 2: A : Optional[Any] =sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(lowercase ) if i < len(lowercase ) - 3: A : Optional[int] =sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(lowercase ) for i in range(0, len(lowercase ) - 1 ): if i < len(lowercase ) - 1: A : Any =cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(lowercase ) if i < len(lowercase ) - 2: A : Tuple =cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(lowercase ) if i < len(lowercase ) - 3: A : Tuple =cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(lowercase ) ((A) , (A) , (A)) : Any =SARIngram(lowercase, lowercase, lowercase, lowercase ) ((A) , (A) , (A)) : List[str] =SARIngram(lowercase, lowercase, lowercase, lowercase ) ((A) , (A) , (A)) : List[Any] =SARIngram(lowercase, lowercase, lowercase, lowercase ) ((A) , (A) , (A)) : List[Any] =SARIngram(lowercase, lowercase, lowercase, lowercase ) A : Any =sum([keepascore, keepascore, keepascore, keepascore] ) / 4 A : Tuple =sum([delascore, delascore, delascore, delascore] ) / 4 A : Union[str, Any] =sum([addascore, addascore, addascore, addascore] ) / 4 A : List[str] =(avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A__ ( lowercase: Any, lowercase: bool = True, lowercase: str = "13a", lowercase: bool = True ) -> str: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: A : Union[str, Any] =sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: A : Union[str, Any] =sacrebleu.metrics.bleu._get_tokenizer(lowercase )()(lowercase ) else: A : Optional[int] =sacrebleu.TOKENIZERS[tokenizer]()(lowercase ) elif tokenizer == "moses": A : Union[str, Any] =sacremoses.MosesTokenizer().tokenize(lowercase, return_str=lowercase, escape=lowercase ) elif tokenizer == "penn": A : Optional[Any] =sacremoses.MosesTokenizer().penn_tokenize(lowercase, return_str=lowercase ) else: A : Dict =sentence if not return_str: A : List[Any] =normalized_sent.split() return normalized_sent def A__ ( lowercase: Union[str, Any], lowercase: int, lowercase: List[str] ) -> int: if not (len(lowercase ) == len(lowercase ) == len(lowercase )): raise ValueError('Sources length must match predictions and references lengths.' ) A : int =0 for src, pred, refs in zip(lowercase, lowercase, lowercase ): sari_score += SARIsent(normalize(lowercase ), normalize(lowercase ), [normalize(lowercase ) for sent in refs] ) A : int =sari_score / len(lowercase ) return 100 * sari_score def A__ ( lowercase: Tuple, lowercase: Any, lowercase: List[Any]="exp", lowercase: Tuple=None, lowercase: Any=False, lowercase: Tuple=False, lowercase: List[str]=False, ) -> str: A : str =len(references[0] ) if any(len(lowercase ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) A : Tuple =[[refs[i] for refs in references] for i in range(lowercase )] A : Tuple =sacrebleu.corpus_bleu( lowercase, lowercase, smooth_method=lowercase, smooth_value=lowercase, force=lowercase, lowercase=lowercase, use_effective_order=lowercase, ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE_ ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Sequence(datasets.Value('string' , id='sequence' ) , id='references' ), } ) , codebase_urls=[ 'https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py', 'https://github.com/cocoxu/simplification/blob/master/SARI.py', 'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py', 'https://github.com/mjpost/sacreBLEU', ] , reference_urls=[ 'https://www.aclweb.org/anthology/Q16-1029.pdf', 'https://github.com/mjpost/sacreBLEU', 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ) -> Any: A : int ={} result.update({'sari': compute_sari(sources=SCREAMING_SNAKE_CASE__ , predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ )} ) result.update({'sacrebleu': compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ )} ) result.update({'exact': compute_em(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ )} ) return result
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
_lowercase : List[Any] =''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' _lowercase : Tuple =[{'''type''': '''code''', '''content''': INSTALL_CONTENT}] _lowercase : List[Any] ={ '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
661
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _lowercase : List[str] =False class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : str =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) A : Optional[int] =torch.manual_seed(0 ) A : Optional[int] =pipe( image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images A : List[Any] =image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) A : int =np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) _lowercase : Optional[int] ={'''configuration_vit''': ['''VIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTConfig''', '''ViTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Tuple =['''ViTFeatureExtractor'''] _lowercase : List[str] =['''ViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] =[ '''VIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTForImageClassification''', '''ViTForMaskedImageModeling''', '''ViTModel''', '''ViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Tuple =[ '''TFViTForImageClassification''', '''TFViTModel''', '''TFViTPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] =[ '''FlaxViTForImageClassification''', '''FlaxViTModel''', '''FlaxViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys _lowercase : List[str] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=_lowerCamelCase ) class SCREAMING_SNAKE_CASE_ ( _lowerCamelCase ): '''simple docstring''' lowercase : str = field(default="audio-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowercase : str = Features({"audio": Audio()} ) lowercase : List[str] = Features({"labels": ClassLabel} ) lowercase : List[str] = "audio" lowercase : int = "labels" def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> int: 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] , A__ ): raise ValueError(f'Column {self.label_column} is not a ClassLabel.' ) A : Union[str, Any] =copy.deepcopy(self ) A : int =self.label_schema.copy() A : Optional[Any] =features[self.label_column] A : Optional[int] =label_schema return task_template @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Dict[str, str]: return { self.audio_column: "audio", self.label_column: "labels", }
700
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
0
def A__ ( lowercase: List[str], lowercase: int, lowercase: Optional[int] ) -> Optional[Any]: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__A, n - 1, __A ) * a) % mod else: A : Optional[int] =binary_exponentiation(__A, n / 2, __A ) return (b * b) % mod # a prime number _lowercase : Dict =7_0_1 _lowercase : Optional[Any] =1_0_0_0_0_0_0_0_0_0 _lowercase : List[Any] =1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
701
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
0
import itertools import math def A__ ( lowercase: Tuple ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A__ ( ) -> List[Any]: A : Optional[int] =2 while True: if is_prime(_SCREAMING_SNAKE_CASE ): yield num num += 1 def A__ ( lowercase: int = 10_001 ) -> int: return next(itertools.islice(prime_generator(), nth - 1, _SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": print(f'''{solution() = }''')
702
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
0
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A__ ( lowercase: str, lowercase: Dict, lowercase: Optional[int] ) -> int: A : Optional[Any] =BertConfig.from_json_file(lowercase ) print(F'Building PyTorch model from configuration: {config}' ) A : str =BertForPreTraining(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase, lowercase, lowercase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict(), lowercase ) if __name__ == "__main__": _lowercase : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : Union[str, Any] =parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
703
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
0
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets _lowercase : Tuple =datasets.logging.get_logger(__name__) _lowercase : Optional[Any] ='''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' _lowercase : Dict ='''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' _lowercase : Union[str, Any] =''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' _lowercase : Dict ={ '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE_ ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/google-research/bleurt' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/bleurt'] , reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] , ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) A : Optional[int] ='bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: A : int =self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: A : Tuple =self.config_name.upper() else: raise KeyError( f'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer A : Optional[Any] =dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) A : str =score.BleurtScorer(os.path.join(UpperCamelCase_ , UpperCamelCase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: A : List[str] =self.scorer.score(references=UpperCamelCase_ , candidates=UpperCamelCase_ ) return {"scores": scores}
704
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
0
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class SCREAMING_SNAKE_CASE_ ( lowercase__ ): '''simple docstring''' lowercase : List[Any] = "Speech2TextFeatureExtractor" lowercase : str = "Speech2TextTokenizer" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) A : str =self.feature_extractor A : Optional[int] =False def __call__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: if self._in_target_context_manager: return self.current_processor(*__lowerCamelCase , **__lowerCamelCase ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) A : Tuple =kwargs.pop('raw_speech' ) else: A : Optional[int] =kwargs.pop('audio' , __lowerCamelCase ) A : Any =kwargs.pop('sampling_rate' , __lowerCamelCase ) A : Optional[int] =kwargs.pop('text' , __lowerCamelCase ) if len(__lowerCamelCase ) > 0: A : List[str] =args[0] A : int =args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: A : List[str] =self.feature_extractor(__lowerCamelCase , *__lowerCamelCase , sampling_rate=__lowerCamelCase , **__lowerCamelCase ) if text is not None: A : str =self.tokenizer(__lowerCamelCase , **__lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: A : List[str] =encodings["input_ids"] return inputs def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @contextmanager def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) A : int =True A : Dict =self.tokenizer yield A : Tuple =self.feature_extractor A : Any =False
705
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
0
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def A__ ( lowercase: Tuple ) -> tuple: return (data["data"], data["target"]) def A__ ( lowercase: Any, lowercase: Optional[Any], lowercase: str ) -> np.ndarray: A : Optional[Any] =XGBRegressor(verbosity=0, random_state=42 ) xgb.fit(lowerCamelCase_, lowerCamelCase_ ) # Predict target for test data A : Union[str, Any] =xgb.predict(lowerCamelCase_ ) A : int =predictions.reshape(len(lowerCamelCase_ ), 1 ) return predictions def A__ ( ) -> None: A : List[str] =fetch_california_housing() A : int =data_handling(lowerCamelCase_ ) A : List[str] =train_test_split( lowerCamelCase_, lowerCamelCase_, test_size=0.25, random_state=1 ) A : Dict =xgboost(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ) # Error printing print(F'Mean Absolute Error : {mean_absolute_error(lowerCamelCase_, lowerCamelCase_ )}' ) print(F'Mean Square Error : {mean_squared_error(lowerCamelCase_, lowerCamelCase_ )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
706
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
0
class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: A : Dict =n A : Dict =[None] * self.n A : Tuple =0 # index of the first element A : List[Any] =0 A : List[Any] =0 def __len__( self : Optional[int] ) -> int: return self.size def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> bool: return self.size == 0 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[Any]: return False if self.is_empty() else self.array[self.front] def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A : Tuple =data A : List[Any] =(self.rear + 1) % self.n self.size += 1 return self def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: if self.size == 0: raise Exception('UNDERFLOW' ) A : Dict =self.array[self.front] A : Tuple =None A : int =(self.front + 1) % self.n self.size -= 1 return temp
707
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
0
class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] ) -> None: A : dict[str, TrieNode] ={} # Mapping from char to TrieNode A : Optional[int] =False def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : list[str] ) -> None: for word in words: self.insert(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> None: A : Optional[int] =self for char in word: if char not in curr.nodes: A : Union[str, Any] =TrieNode() A : List[Any] =curr.nodes[char] A : Union[str, Any] =True def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ) -> bool: A : List[Any] =self for char in word: if char not in curr.nodes: return False A : Tuple =curr.nodes[char] return curr.is_leaf def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : str ) -> None: def _delete(SCREAMING_SNAKE_CASE__ : TrieNode , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ) -> bool: if index == len(SCREAMING_SNAKE_CASE__ ): # If word does not exist if not curr.is_leaf: return False A : Union[str, Any] =False return len(curr.nodes ) == 0 A : Dict =word[index] A : Dict =curr.nodes.get(SCREAMING_SNAKE_CASE__ ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted A : Optional[int] =_delete(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE__ , 0 ) def A__ ( lowercase: TrieNode, lowercase: str ) -> None: if node.is_leaf: print(__A, end=' ' ) for key, value in node.nodes.items(): print_words(__A, word + key ) def A__ ( ) -> bool: A : Union[str, Any] ='''banana bananas bandana band apple all beast'''.split() A : Dict =TrieNode() root.insert_many(__A ) # print_words(root, "") assert all(root.find(__A ) for word in words ) assert root.find('banana' ) assert not root.find('bandanas' ) assert not root.find('apps' ) assert root.find('apple' ) assert root.find('all' ) root.delete('all' ) assert not root.find('all' ) root.delete('banana' ) assert not root.find('banana' ) assert root.find('bananas' ) return True def A__ ( lowercase: str, lowercase: bool ) -> None: print(str(__A ), 'works!' if passes else 'doesn\'t work :(' ) def A__ ( ) -> None: assert test_trie() def A__ ( ) -> None: print_results('Testing trie functionality', test_trie() ) if __name__ == "__main__": main()
708
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
0
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict=13 , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Optional[int]=99 , SCREAMING_SNAKE_CASE__ : Optional[Any]=32 , SCREAMING_SNAKE_CASE__ : str=5 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : Any=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : str=5_12 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Dict=0.0_2 , SCREAMING_SNAKE_CASE__ : str=4 , ) -> Union[str, Any]: A : Union[str, Any] =parent A : List[str] =batch_size A : Any =seq_length A : Optional[Any] =is_training A : Dict =use_attention_mask A : str =use_token_type_ids A : Union[str, Any] =use_labels A : Optional[int] =vocab_size A : List[Any] =hidden_size A : Dict =num_hidden_layers A : str =num_attention_heads A : Dict =intermediate_size A : Dict =hidden_act A : Optional[int] =hidden_dropout_prob A : List[Any] =attention_probs_dropout_prob A : List[Any] =max_position_embeddings A : Any =type_vocab_size A : Optional[Any] =type_sequence_label_size A : Any =initializer_range A : Tuple =num_choices def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Tuple =None if self.use_attention_mask: A : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) A : Tuple =None if self.use_token_type_ids: A : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : Optional[Any] =RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: A : str =self.prepare_config_and_inputs() A , A , A , A : Union[str, Any] =config_and_inputs A : int ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Union[str, Any] = True lowercase : str = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> str: A : List[str] =FlaxRoFormerModelTester(self ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Dict: for model_class_name in self.all_model_classes: A : str =model_class_name.from_pretrained('junnyu/roformer_chinese_small' , from_pt=_lowerCAmelCase ) A : int =model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCAmelCase ) @require_flax class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Any: A : Tuple =FlaxRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) A : List[str] =jnp.array([[0, 1, 2, 3, 4, 5]] ) A : Union[str, Any] =model(_lowerCAmelCase )[0] A : Tuple =5_00_00 A : Dict =(1, 6, vocab_size) self.assertEqual(output.shape , _lowerCAmelCase ) A : List[str] =jnp.array( [[[-0.1_2_0_5, -1.0_2_6_5, 0.2_9_2_2], [-1.5_1_3_4, 0.1_9_7_4, 0.1_5_1_9], [-5.0_1_3_5, -3.9_0_0_3, -0.8_4_0_4]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _lowerCAmelCase , atol=1e-4 ) )
709
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, 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=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=7 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=99 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=32 , SCREAMING_SNAKE_CASE__ : List[Any]=5 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Any=5_12 , SCREAMING_SNAKE_CASE__ : str=16 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : str=0.0_2 , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : str=4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Union[str, Any]: A : Union[str, Any] =parent A : Dict =batch_size A : str =seq_length A : Union[str, Any] =is_training A : Tuple =use_token_type_ids A : Union[str, Any] =use_labels A : str =vocab_size A : Optional[Any] =hidden_size A : Tuple =num_hidden_layers A : Optional[Any] =num_attention_heads A : int =intermediate_size A : Optional[Any] =hidden_act A : Dict =hidden_dropout_prob A : List[str] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : str =type_vocab_size A : List[Any] =type_sequence_label_size A : Optional[int] =initializer_range A : int =num_labels A : Any =num_choices A : Dict =scope A : str =self.vocab_size - 1 def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[Any]: A : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : str =None if self.use_token_type_ids: A : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : Dict =None A : Optional[int] =None A : str =None if self.use_labels: A : Union[str, Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Dict =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Optional[Any] =ids_tensor([self.batch_size] , self.num_choices ) A : List[str] =OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) A : Optional[Any] =ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: A : str =OpenAIGPTModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() A : List[str] =model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , head_mask=UpperCamelCase_ ) A : Any =model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ ) A : Union[str, Any] =model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Any ) -> str: A : Any =OpenAIGPTLMHeadModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() A : List[Any] =model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , *SCREAMING_SNAKE_CASE__ : Tuple ) -> int: A : Any =OpenAIGPTDoubleHeadsModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() A : str =model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: A : Tuple =self.num_labels A : int =OpenAIGPTForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() A : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple =model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: A : int =self.prepare_config_and_inputs() ( A ) : Union[str, Any] =config_and_inputs A : List[str] ={ "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Union[str, Any] = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase : Optional[int] = ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False ) -> str: A : Union[str, Any] =super()._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": A : List[str] =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase_ , ) A : str =inputs_dict["labels"] A : int =inputs_dict["labels"] A : List[Any] =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=UpperCamelCase_ , ) A : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) return inputs_dict def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Union[str, Any] =OpenAIGPTModelTester(self ) A : Optional[int] =ConfigTester(self , config_class=UpperCamelCase_ , n_embd=37 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: A : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*UpperCamelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCamelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: A : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*UpperCamelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: A : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCamelCase_ ) @slow def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[Any]: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : Dict =OpenAIGPTModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @require_torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Any =OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(UpperCamelCase_ ) A : Any =torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=UpperCamelCase_ ) # the president is A : List[str] =[ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the A : Tuple =model.generate(UpperCamelCase_ , do_sample=UpperCamelCase_ ) self.assertListEqual(output_ids[0].tolist() , UpperCamelCase_ )
710
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A : Optional[int] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : str =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : Optional[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A : Tuple ='base imports' if key == 'none' else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\n'.join(F'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
661
0
from __future__ import annotations class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : List[str] =text, pattern A : Any =len(__A ), len(__A ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: # searches pattern in text and returns index positions A : List[str] =[] for i in range(self.textLen - self.patLen + 1 ): A : int =self.mismatch_in_text(__A ) if mismatch_index == -1: positions.append(__A ) else: A : List[str] =self.match_in_pattern(self.text[mismatch_index] ) A : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions _lowercase : int ='ABAABA' _lowercase : List[str] ='AB' _lowercase : Tuple =BoyerMooreSearch(text, pattern) _lowercase : List[str] =bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
711
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
0
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
712
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> str: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
0
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 _lowercase : List[Any] =logging.get_logger(__name__) _lowercase : List[Any] ={ '''sail/poolformer_s12''': '''https://huggingface.co/sail/poolformer_s12/resolve/main/config.json''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class SCREAMING_SNAKE_CASE_ ( _snake_case ): '''simple docstring''' lowercase : int = 'poolformer' def __init__( self : Any , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : str=16 , SCREAMING_SNAKE_CASE__ : Dict=16 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : List[str]=4.0 , SCREAMING_SNAKE_CASE__ : List[Any]=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[64, 1_28, 3_20, 5_12] , SCREAMING_SNAKE_CASE__ : int=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE__ : List[str]=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE__ : Any=[2, 1, 1, 1] , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Dict=1e-5 , SCREAMING_SNAKE_CASE__ : Dict=0.0_2 , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: A : Union[str, Any] =num_channels A : Tuple =patch_size A : List[str] =stride A : Union[str, Any] =padding A : Tuple =pool_size A : Any =hidden_sizes A : Tuple =mlp_ratio A : List[Any] =depths A : Any =patch_sizes A : Union[str, Any] =strides A : List[Any] =num_encoder_blocks A : Union[str, Any] =drop_path_rate A : Tuple =hidden_act A : List[Any] =use_layer_scale A : int =layer_scale_init_value A : Union[str, Any] =initializer_range super().__init__(**SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE_ ( _snake_case ): '''simple docstring''' lowercase : List[str] = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> Union[str, Any]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: return 2e-3
713
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
0
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase : Dict =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Tuple ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' , _UpperCAmelCase , ) super().__init__(*_UpperCAmelCase , **_UpperCAmelCase )
714
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 ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml _lowercase : Union[str, Any] =logging.get_logger(__name__) def A__ ( lowercase: List[str], lowercase: int ) -> Optional[int]: def run_func(lowercase: Optional[int] ): @wraps(__A ) def run_in_eager_mode(*lowercase: Union[str, Any], **lowercase: Optional[int] ): return func(*__A, **__A ) @wraps(__A ) @tf.function(experimental_compile=__A ) def run_in_graph_mode(*lowercase: Union[str, Any], **lowercase: List[Any] ): return func(*__A, **__A ) if do_eager_mode is True: if use_xla is not False: raise ValueError( 'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def A__ ( lowercase: Any, lowercase: Any, lowercase: Any ) -> Optional[Any]: A : Union[str, Any] =random.Random() A : Any =[rng.randint(0, vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(__A, shape=(batch_size, sequence_length), dtype=tf.intaa ) class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): '''simple docstring''' lowercase : int = 42 lowercase : int = 42 lowercase : List[str] = "TensorFlow" @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[str]: return tf.__version__ def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: A : List[str] =self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) A : Optional[Any] =self._prepare_inference_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_speed(_inference ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: A : List[Any] =self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) A : str =self._prepare_train_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_speed(_train ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> [Memory, Optional[MemorySummary]]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _UpperCamelCase ) A : Optional[Any] =self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) A : List[Any] =self._prepare_inference_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_memory(_inference ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> [Memory, Optional[MemorySummary]]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _UpperCamelCase ) A : Optional[int] =self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) A : Optional[int] =self._prepare_train_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_memory(_train ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Callable[[], None]: A : Tuple =self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) A : Dict =( hasattr(_UpperCamelCase , 'architectures' ) and isinstance(config.architectures , _UpperCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: A : Dict ="""TF""" + config.architectures[0] # prepend 'TF' for tensorflow model A : List[Any] =__import__('transformers' , fromlist=[model_class] ) A : int =getattr(_UpperCamelCase , _UpperCamelCase ) A : int =model_cls(_UpperCamelCase ) except ImportError: raise ImportError( f'{model_class} does not exist. If you just want to test the pretrained model, you might want to' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: A : List[Any] =TF_MODEL_MAPPING[config.__class__](_UpperCamelCase ) # encoder-decoder has vocab size saved differently A : int =config.vocab_size if hasattr(_UpperCamelCase , 'vocab_size' ) else config.encoder.vocab_size A : List[Any] =random_input_ids(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase , training=_UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_UpperCamelCase , training=_UpperCamelCase ) A : Union[str, Any] =encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Callable[[], None]: A : Any =self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' ) if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) A : List[str] =( hasattr(_UpperCamelCase , 'architectures' ) and isinstance(config.architectures , _UpperCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: A : Union[str, Any] ="""TF""" + config.architectures[0] # prepend 'TF' for tensorflow model A : str =__import__('transformers' , fromlist=[model_class] ) A : int =getattr(_UpperCamelCase , _UpperCamelCase ) A : Optional[int] =model_cls(_UpperCamelCase ) except ImportError: raise ImportError( f'{model_class} does not exist. If you just want to test the pretrained model, you might want to' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: A : List[str] =TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_UpperCamelCase ) # encoder-decoder has vocab size saved differently A : int =config.vocab_size if hasattr(_UpperCamelCase , 'vocab_size' ) else config.encoder.vocab_size A : Union[str, Any] =random_input_ids(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): A : Dict =model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase , labels=_UpperCamelCase , training=_UpperCamelCase )[0] A : int =tf.gradients(_UpperCamelCase , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): A : Dict =model(_UpperCamelCase , labels=_UpperCamelCase , training=_UpperCamelCase )[0] A : Any =tf.gradients(_UpperCamelCase , model.trainable_variables ) return gradients A : List[str] =encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> float: with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' ) timeit.repeat(_UpperCamelCase , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average A : Tuple =timeit.repeat( _UpperCamelCase , repeat=self.args.repeat , number=10 , ) return min(_UpperCamelCase ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f'Doesn\'t fit on GPU. {e}' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Callable[[], None] ) -> [Memory, MemorySummary]: logger.info( 'Note that TensorFlow allocates more memory than ' 'it might need to speed up computation. ' 'The memory reported here corresponds to the memory ' 'reported by `nvidia-smi`, which can vary depending ' 'on total available memory on the GPU that is used.' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory' ' consumption line by line.' ) A : List[str] =start_memory_tracing('transformers' ) if self.args.is_tpu: # tpu raise NotImplementedError( 'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking' ' with `args.memory=False`' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( 'py3nvml not installed, we won\'t log GPU memory usage. ' 'Install py3nvml (pip install py3nvml) to log information about GPU.' ) A : Optional[Any] ="""N/A""" else: logger.info( 'Measuring total GPU usage on GPU device. Make sure to not have additional processes' ' running on the same GPU.' ) # init nvml nvml.nvmlInit() func() A : Optional[int] =nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) A : Optional[Any] =nvml.nvmlDeviceGetMemoryInfo(_UpperCamelCase ) A : int =meminfo.used A : List[Any] =Memory(_UpperCamelCase ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( 'When enabling line by line tracing, the max peak memory for CPU is inaccurate in' ' TensorFlow.' ) A : str =None else: A : Union[str, Any] =measure_peak_memory_cpu(_UpperCamelCase ) A : List[Any] =Memory(_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else memory_bytes if self.args.trace_memory_line_by_line: A : Any =stop_memory_tracing(_UpperCamelCase ) if memory is None: A : Union[str, Any] =summary.total else: A : List[str] =None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'Doesn\'t fit on GPU. {e}' ) return "N/A", None
715
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Optional[int] ={ '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] =[ '''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 _lowercase : Union[str, Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
716
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
0
from manim import * class SCREAMING_SNAKE_CASE_ ( _A ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[Any]: A : Dict =Rectangle(height=0.5 , width=0.5 ) A : Any =Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) A : Tuple =[mem.copy() for i in range(6 )] A : List[Any] =[mem.copy() for i in range(6 )] A : Optional[int] =VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : Optional[int] =VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : int =VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : Tuple =Text('CPU' , font_size=24 ) A : Tuple =Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__lowerCamelCase ) A : Any =[mem.copy() for i in range(4 )] A : List[Any] =VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : List[str] =Text('GPU' , font_size=24 ) A : List[Any] =Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(__lowerCamelCase ) A : int =[mem.copy() for i in range(6 )] A : Optional[Any] =VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : Optional[Any] =Text('Model' , font_size=24 ) A : int =Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(__lowerCamelCase ) A : List[str] =[] for i, rect in enumerate(__lowerCamelCase ): rect.set_stroke(__lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) A : Optional[Any] =Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=__lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 ) self.add(__lowerCamelCase ) cpu_targs.append(__lowerCamelCase ) A : Any =[mem.copy() for i in range(6 )] A : str =VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 ) A : List[Any] =Text('Loaded Checkpoint' , font_size=24 ) A : List[str] =Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) A : int =Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) A : Union[str, Any] =MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__lowerCamelCase , __lowerCamelCase ) A : List[Any] =MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) A : Dict =MarkupText( f'Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) ) self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) ) A : int =[] A : str =[] for i, rect in enumerate(__lowerCamelCase ): A : List[Any] =fill.copy().set_fill(__lowerCamelCase , opacity=0.7 ) target.move_to(__lowerCamelCase ) first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) ) A : Optional[int] =target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) ) self.play(*__lowerCamelCase ) self.play(*__lowerCamelCase ) self.wait()
717
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase : Any ={ "configuration_biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig"], "tokenization_biogpt": ["BioGptTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str =[ "BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "BioGptForCausalLM", "BioGptForTokenClassification", "BioGptForSequenceClassification", "BioGptModel", "BioGptPreTrainedModel", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys _lowercase : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
718
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
0
import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: if isinstance(__UpperCamelCase , __UpperCamelCase ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden A : List[Any] =deepcopy(__UpperCamelCase ) elif os.path.exists(__UpperCamelCase ): with io.open(__UpperCamelCase , 'r' , encoding='utf-8' ) as f: A : str =json.load(__UpperCamelCase ) else: try: A : str =baseaa.urlsafe_baadecode(__UpperCamelCase ).decode('utf-8' ) A : Union[str, Any] =json.loads(__UpperCamelCase ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( f'Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}' ) A : Any =config self.set_stage_and_offload() def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_value('zero_optimization.stage' , -1 ) # offload A : Union[str, Any] =False if self.is_zeroa() or self.is_zeroa(): A : Optional[int] =set(['cpu', 'nvme'] ) A : Tuple =set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: A : Optional[Any] =True def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: A : Any =self.config # find the config node of interest if it exists A : int =ds_key_long.split('.' ) A : Union[str, Any] =nodes.pop() for node in nodes: A : Any =config.get(__UpperCamelCase ) if config is None: return None, ds_key return config, ds_key def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Optional[Any]: A , A : List[str] =self.find_config_node(__UpperCamelCase ) if config is None: return default return config.get(__UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]=False ) -> List[Any]: A : List[str] =self.config # find the config node of interest if it exists A : Union[str, Any] =ds_key_long.split('.' ) for node in nodes: A : Optional[int] =config A : Tuple =config.get(__UpperCamelCase ) if config is None: if must_exist: raise ValueError(f'Can\'t find {ds_key_long} entry in the config: {self.config}' ) else: return # if found remove it if parent_config is not None: parent_config.pop(__UpperCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: A : List[Any] =self.get_value(__UpperCamelCase ) return False if value is None else bool(__UpperCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : str =self.get_value(__UpperCamelCase ) return False if value is None else not bool(__UpperCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: return self._stage == 2 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return self._stage == 3 def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[str]: return self._offload class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: A : Dict =engine def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: self.engine.backward(__UpperCamelCase , **__UpperCamelCase ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: super().__init__(__UpperCamelCase , device_placement=__UpperCamelCase , scaler=__UpperCamelCase ) A : int =hasattr(self.optimizer , 'overflow' ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : str=None ) -> Optional[int]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[str]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.__has_overflow__: return self.optimizer.overflow return False class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: super().__init__(__UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int=0.0_0_1 , SCREAMING_SNAKE_CASE__ : Dict=0 , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: A : Union[str, Any] =params A : Dict =lr A : Any =weight_decay A : Optional[Any] =kwargs class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : List[Any]=0 , **SCREAMING_SNAKE_CASE__ : List[str] ) -> int: A : List[str] =optimizer A : Optional[Any] =total_num_steps A : Union[str, Any] =warmup_num_steps A : Union[str, Any] =kwargs
719
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowercase : Optional[Any] =logging.get_logger(__name__) _lowercase : Dict ={ """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""", """self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""", """self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""", """self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""", """self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""", """self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""", """self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""", """self_attn.rotary_emb""": """encoder.embed_positions""", """self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""", """conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""", """conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""", """conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""", """conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""", """conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""", """ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""", """ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""", """ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""", """ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""", """ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""", """ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } _lowercase : str =[ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def A__ ( lowercase: Any, lowercase: Optional[int], lowercase: Optional[Any], lowercase: str, lowercase: Optional[Any] ) -> Optional[Any]: for attribute in key.split('.' ): A : List[str] =getattr(lowercase, lowercase ) if weight_type is not None: A : Dict =getattr(lowercase, lowercase ).shape else: A : Any =hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": A : int =value elif weight_type == "weight_g": A : int =value elif weight_type == "weight_v": A : Tuple =value elif weight_type == "bias": A : Optional[Any] =value elif weight_type == "running_mean": A : Union[str, Any] =value elif weight_type == "running_var": A : Optional[Any] =value elif weight_type == "num_batches_tracked": A : Optional[Any] =value elif weight_type == "inv_freq": A : List[str] =value else: A : int =value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Union[str, Any] ) -> Union[str, Any]: A : List[Any] =[] A : str =fairseq_model.state_dict() A : Union[str, Any] =hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): A : Optional[int] =False if "conv_layers" in name: load_conv_layer( lowercase, lowercase, lowercase, lowercase, hf_model.config.feat_extract_norm == 'group', ) A : Any =True else: for key, mapped_key in MAPPING.items(): A : Optional[Any] ='wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: A : List[str] =True if "*" in mapped_key: A : str =name.split(lowercase )[0].split('.' )[-2] A : List[Any] =mapped_key.replace('*', lowercase ) if "pos_bias_u" in name: A : Union[str, Any] =None elif "pos_bias_v" in name: A : str =None elif "weight_g" in name: A : Tuple ='weight_g' elif "weight_v" in name: A : Dict ='weight_v' elif "bias" in name: A : Optional[Any] ='bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj A : Optional[Any] ='weight' elif "running_mean" in name: A : List[Any] ='running_mean' elif "inv_freq" in name: A : Optional[Any] ='inv_freq' elif "running_var" in name: A : Tuple ='running_var' elif "num_batches_tracked" in name: A : str ='num_batches_tracked' else: A : Optional[int] =None set_recursively(lowercase, lowercase, lowercase, lowercase, lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(F'Unused weights: {unused_weights}' ) def A__ ( lowercase: int, lowercase: Dict, lowercase: List[str], lowercase: Union[str, Any], lowercase: str ) -> List[Any]: A : Optional[Any] =full_name.split('conv_layers.' )[-1] A : Any =name.split('.' ) A : Optional[Any] =int(items[0] ) A : Tuple =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) A : Optional[Any] =value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) A : Optional[int] =value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) A : List[Any] =value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) A : List[Any] =value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowercase ) @torch.no_grad() def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Dict=None, lowercase: Tuple=None, lowercase: str=True ) -> Any: if config_path is not None: A : Optional[int] =WavaVecaConformerConfig.from_pretrained(lowercase, hidden_act='swish' ) else: A : int =WavaVecaConformerConfig() if "rope" in checkpoint_path: A : List[Any] ='rotary' if is_finetuned: if dict_path: A : List[Any] =Dictionary.load(lowercase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq A : Tuple =target_dict.pad_index A : Any =target_dict.bos_index A : Dict =target_dict.eos_index A : List[Any] =len(target_dict.symbols ) A : Union[str, Any] =os.path.join(lowercase, 'vocab.json' ) if not os.path.isdir(lowercase ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(lowercase ) ) return os.makedirs(lowercase, exist_ok=lowercase ) A : List[Any] =target_dict.indices # fairseq has the <pad> and <s> switched A : Union[str, Any] =0 A : Any =1 with open(lowercase, 'w', encoding='utf-8' ) as vocab_handle: json.dump(lowercase, lowercase ) A : Optional[Any] =WavaVecaCTCTokenizer( lowercase, unk_token=target_dict.unk_word, pad_token=target_dict.pad_word, bos_token=target_dict.bos_word, eos_token=target_dict.eos_word, word_delimiter_token='|', do_lower_case=lowercase, ) A : Optional[Any] =True if config.feat_extract_norm == 'layer' else False A : Tuple =WavaVecaFeatureExtractor( feature_size=1, sampling_rate=16_000, padding_value=0, do_normalize=lowercase, return_attention_mask=lowercase, ) A : Tuple =WavaVecaProcessor(feature_extractor=lowercase, tokenizer=lowercase ) processor.save_pretrained(lowercase ) A : Dict =WavaVecaConformerForCTC(lowercase ) else: A : Optional[int] =WavaVecaConformerForPreTraining(lowercase ) if is_finetuned: A , A , A : List[str] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: A : Tuple =argparse.Namespace(task='audio_pretraining' ) A : Union[str, Any] =fairseq.tasks.setup_task(lowercase ) A , A , A : int =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path], task=lowercase ) A : str =model[0].eval() recursively_load_weights(lowercase, lowercase, not is_finetuned ) hf_wavavec.save_pretrained(lowercase ) if __name__ == "__main__": _lowercase : Dict =argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) _lowercase : Any =parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
720
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
0
from __future__ import annotations import math import random from typing import Any class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : int ) -> None: A : list[Any] =[] A : int =0 A : int =0 def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> bool: return self.head == self.tail def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> None: self.data.append(_lowercase ) A : Union[str, Any] =self.tail + 1 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =self.data[self.head] A : Any =self.head + 1 return ret def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> int: return self.tail - self.head def SCREAMING_SNAKE_CASE_ ( self : Any ) -> None: print(self.data ) print('**************' ) print(self.data[self.head : self.tail] ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> None: A : Optional[int] =data A : MyNode | None =None A : MyNode | None =None A : int =1 def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: return self.data def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> MyNode | None: return self.left def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> MyNode | None: return self.right def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: return self.height def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> None: A : List[str] =data def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> None: A : int =node def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> None: A : int =node def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> None: A : Union[str, Any] =height def A__ ( lowercase: MyNode | None ) -> int: if node is None: return 0 return node.get_height() def A__ ( lowercase: int, lowercase: int ) -> Optional[int]: if a > b: return a return b def A__ ( lowercase: MyNode ) -> List[Any]: print('left rotation node:', node.get_data() ) A : List[str] =node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(__UpperCamelCase ) A : List[str] =my_max(get_height(node.get_right() ), get_height(node.get_left() ) ) + 1 node.set_height(__UpperCamelCase ) A : Tuple =my_max(get_height(ret.get_right() ), get_height(ret.get_left() ) ) + 1 ret.set_height(__UpperCamelCase ) return ret def A__ ( lowercase: MyNode ) -> str: print('right rotation node:', node.get_data() ) A : Tuple =node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(__UpperCamelCase ) A : List[Any] =my_max(get_height(node.get_right() ), get_height(node.get_left() ) ) + 1 node.set_height(__UpperCamelCase ) A : List[Any] =my_max(get_height(ret.get_right() ), get_height(ret.get_left() ) ) + 1 ret.set_height(__UpperCamelCase ) return ret def A__ ( lowercase: MyNode ) -> Tuple: A : List[str] =node.get_left() assert left_child is not None node.set_left(left_rotation(__UpperCamelCase ) ) return right_rotation(__UpperCamelCase ) def A__ ( lowercase: MyNode ) -> List[Any]: A : Optional[int] =node.get_right() assert right_child is not None node.set_right(right_rotation(__UpperCamelCase ) ) return left_rotation(__UpperCamelCase ) def A__ ( lowercase: MyNode | None, lowercase: Any ) -> str: if node is None: return MyNode(__UpperCamelCase ) if data < node.get_data(): node.set_left(insert_node(node.get_left(), __UpperCamelCase ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected A : int =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 A : Optional[Any] =right_rotation(__UpperCamelCase ) else: A : List[str] =lr_rotation(__UpperCamelCase ) else: node.set_right(insert_node(node.get_right(), __UpperCamelCase ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: A : Optional[Any] =node.get_right() assert right_child is not None if data < right_child.get_data(): A : Optional[Any] =rl_rotation(__UpperCamelCase ) else: A : int =left_rotation(__UpperCamelCase ) A : Optional[Any] =my_max(get_height(node.get_right() ), get_height(node.get_left() ) ) + 1 node.set_height(__UpperCamelCase ) return node def A__ ( lowercase: MyNode ) -> Any: while True: A : Union[str, Any] =root.get_right() if right_child is None: break A : List[Any] =right_child return root.get_data() def A__ ( lowercase: MyNode ) -> List[str]: while True: A : List[str] =root.get_left() if left_child is None: break A : str =left_child return root.get_data() def A__ ( lowercase: MyNode, lowercase: Any ) -> Union[str, Any]: A : List[str] =root.get_left() A : List[Any] =root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: A : Tuple =get_left_most(__UpperCamelCase ) root.set_data(__UpperCamelCase ) root.set_right(del_node(__UpperCamelCase, __UpperCamelCase ) ) elif left_child is not None: A : str =left_child elif right_child is not None: A : Optional[Any] =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(__UpperCamelCase, __UpperCamelCase ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(__UpperCamelCase, __UpperCamelCase ) ) if get_height(__UpperCamelCase ) - get_height(__UpperCamelCase ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): A : List[Any] =left_rotation(__UpperCamelCase ) else: A : Optional[int] =rl_rotation(__UpperCamelCase ) elif get_height(__UpperCamelCase ) - get_height(__UpperCamelCase ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): A : Union[str, Any] =right_rotation(__UpperCamelCase ) else: A : Union[str, Any] =lr_rotation(__UpperCamelCase ) A : List[str] =my_max(get_height(root.get_right() ), get_height(root.get_left() ) ) + 1 root.set_height(__UpperCamelCase ) return root class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] ) -> None: A : MyNode | None =None def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> int: return get_height(self.root ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : int ) -> None: print('insert:' + str(_lowercase ) ) A : List[str] =insert_node(self.root , _lowercase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ) -> None: print('delete:' + str(_lowercase ) ) if self.root is None: print('Tree is empty!' ) return A : str =del_node(self.root , _lowercase ) def __str__( self : List[Any] , ) -> str: # a level traversale, gives a more intuitive look on the tree A : Dict ="""""" A : List[Any] =MyQueue() q.push(self.root ) A : Optional[Any] =self.get_height() if layer == 0: return output A : Union[str, Any] =0 while not q.is_empty(): A : str =q.pop() A : Dict =""" """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(_lowercase ) q.push(_lowercase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space A : Tuple =cnt + 1 for i in range(1_00 ): if cnt == math.pow(2 , _lowercase ) - 1: A : List[Any] =layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def A__ ( ) -> Optional[Any]: import doctest doctest.testmod() if __name__ == "__main__": _test() _lowercase : Dict =AVLtree() _lowercase : List[str] =list(range(1_0)) 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))
721
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
0
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def A__ ( lowercase: dict ) -> int: return (data["data"], data["target"]) def A__ ( lowercase: np.ndarray, lowercase: np.ndarray, lowercase: np.ndarray ) -> Union[str, Any]: A : Any =XGBRegressor(verbosity=0, random_state=42 ) xgb.fit(snake_case__, snake_case__ ) # Predict target for test data A : Optional[Any] =xgb.predict(snake_case__ ) A : Tuple =predictions.reshape(len(snake_case__ ), 1 ) return predictions def A__ ( ) -> Tuple: A : Optional[int] =fetch_california_housing() A , A : Dict =data_handling(snake_case__ ) A , A , A , A : Any =train_test_split( snake_case__, snake_case__, test_size=0.25, random_state=1 ) A : int =xgboost(snake_case__, snake_case__, snake_case__ ) # Error printing print(F'Mean Absolute Error : {mean_absolute_error(snake_case__, snake_case__ )}' ) print(F'Mean Square Error : {mean_squared_error(snake_case__, snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
700
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: A : Optional[int] =AutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' , return_dict=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) A : Dict =AutoTokenizer.from_pretrained('google/mt5-small' ) A : Any =tokenizer('Hello there' , return_tensors='pt' ).input_ids A : List[str] =tokenizer('Hi I am' , return_tensors='pt' ).input_ids A : str =model(input_ids.to(SCREAMING_SNAKE_CASE__ ) , labels=labels.to(SCREAMING_SNAKE_CASE__ ) ).loss A : Optional[int] =-(labels.shape[-1] * loss.item()) A : Union[str, Any] =-8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
701
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
0
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) _lowercase : Any =logging.getLogger() def A__ ( lowercase: Path, lowercase: list ) -> Union[str, Any]: A : Optional[Any] ='\n'.join(lowercase ) Path(lowercase ).open('w' ).writelines(lowercase ) _lowercase : int ='''patrickvonplaten/t5-tiny-random''' _lowercase : List[str] ='''sshleifer/bart-tiny-random''' _lowercase : List[Any] ='''sshleifer/tiny-mbart''' _lowercase : str =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: A : Dict =Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' A : List[Any] =input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() A : Any =[' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'] _dump_articles(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Dict =str(Path(self.get_auto_remove_tmp_dir() ) / 'scores.json' ) A : List[Any] ='translation_en_to_de' if model == T5_TINY else 'summarization' A : Union[str, Any] =f'\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n '.split() with patch.object(SCREAMING_SNAKE_CASE__ , 'argv' , SCREAMING_SNAKE_CASE__ ): run_generate() assert Path(SCREAMING_SNAKE_CASE__ ).exists() # os.remove(Path(output_file_name)) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: self.run_eval_tester(SCREAMING_SNAKE_CASE__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: self.run_eval_tester(SCREAMING_SNAKE_CASE__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: A : int =Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' A : int =input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() A : List[str] ={ 'en': ['Machine learning is great, isn\'t it?', 'I like to eat bananas', 'Tomorrow is another great day!'], 'de': [ 'Maschinelles Lernen ist großartig, oder?', 'Ich esse gerne Bananen', 'Morgen ist wieder ein toller Tag!', ], } A : Union[str, Any] =Path(self.get_auto_remove_tmp_dir() ) A : Optional[int] =str(tmp_dir / 'scores.json' ) A : List[Any] =str(tmp_dir / 'val.target' ) _dump_articles(SCREAMING_SNAKE_CASE__ , text['en'] ) _dump_articles(SCREAMING_SNAKE_CASE__ , text['de'] ) A : Tuple ='translation_en_to_de' if model == T5_TINY else 'summarization' A : Tuple =f'\n run_eval_search.py\n {model}\n {str(SCREAMING_SNAKE_CASE__ )}\n {str(SCREAMING_SNAKE_CASE__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n '.split() testargs.extend(['--search', 'num_beams=1:2 length_penalty=0.9:1.0'] ) with patch.object(SCREAMING_SNAKE_CASE__ , 'argv' , SCREAMING_SNAKE_CASE__ ): with CaptureStdout() as cs: run_search() A : Union[str, Any] =[' num_beams | length_penalty', model, 'Best score args'] A : List[str] =['Info'] if "translation" in task: expected_strings.append('bleu' ) else: expected_strings.extend(SCREAMING_SNAKE_CASE__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(SCREAMING_SNAKE_CASE__ ).exists() os.remove(Path(SCREAMING_SNAKE_CASE__ ) )
702
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Union[str, Any] =logging.get_logger(__name__) _lowercase : Dict ={ """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE_ ( UpperCamelCase_ ): '''simple docstring''' lowercase : Dict = "deberta-v2" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=12_81_00 , SCREAMING_SNAKE_CASE__ : Any=15_36 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=24 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Any=61_44 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Dict=5_12 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : str=1e-7 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : str=-1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : Any="gelu" , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> Any: super().__init__(**__A ) A : Optional[int] =hidden_size A : Union[str, Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Tuple =intermediate_size A : Union[str, Any] =hidden_act A : Any =hidden_dropout_prob A : Tuple =attention_probs_dropout_prob A : Tuple =max_position_embeddings A : List[Any] =type_vocab_size A : int =initializer_range A : List[Any] =relative_attention A : Dict =max_relative_positions A : Any =pad_token_id A : Any =position_biased_input # Backwards compatibility if type(__A ) == str: A : List[Any] =[x.strip() for x in pos_att_type.lower().split('|' )] A : List[str] =pos_att_type A : Tuple =vocab_size A : List[str] =layer_norm_eps A : List[str] =kwargs.get('pooler_hidden_size' , __A ) A : Tuple =pooler_dropout A : str =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( UpperCamelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Union[str, Any]: if self.task == "multiple-choice": A : int ={0: "batch", 1: "choice", 2: "sequence"} else: A : List[Any] ={0: "batch", 1: "sequence"} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> int: A : int =super().generate_dummy_inputs(preprocessor=__A , framework=__A ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
703
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
0
import math import sys def A__ ( lowercase: str ) -> Optional[int]: A : Union[str, Any] ="" try: with open(_lowerCamelCase, 'rb' ) as binary_file: A : Tuple =binary_file.read() for dat in data: A : List[str] =F'{dat:08b}' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def A__ ( lowercase: str ) -> Optional[Any]: A : int ={"0": "0", "1": "1"} A : Optional[int] ="", "" A : str =len(_lowerCamelCase ) for i in range(len(_lowerCamelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue A : Union[str, Any] =lexicon[curr_string] result += last_match_id A : int =last_match_id + "0" if math.loga(_lowerCamelCase ).is_integer(): A : Any ={} for curr_key in list(_lowerCamelCase ): A : Optional[Any] =lexicon.pop(_lowerCamelCase ) A : Union[str, Any] =new_lex A : List[str] =last_match_id + "1" index += 1 A : Optional[Any] ="" return result def A__ ( lowercase: str, lowercase: str ) -> Union[str, Any]: A : Any =8 try: with open(_lowerCamelCase, 'wb' ) as opened_file: A : str =[ to_write[i : i + byte_length] for i in range(0, len(_lowerCamelCase ), _lowerCamelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(_lowerCamelCase, 2 ).to_bytes(1, byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def A__ ( lowercase: str ) -> Optional[Any]: A : str =0 for letter in data_bits: if letter == "1": break counter += 1 A : int =data_bits[counter:] A : Union[str, Any] =data_bits[counter + 1 :] return data_bits def A__ ( lowercase: str, lowercase: str ) -> int: A : Dict =read_file_binary(_lowerCamelCase ) A : Any =remove_prefix(_lowerCamelCase ) A : List[Any] =decompress_data(_lowerCamelCase ) write_file_binary(_lowerCamelCase, _lowerCamelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
704
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: A : Optional[int] =AutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' , return_dict=_a ).to(_a ) A : int =AutoTokenizer.from_pretrained('google/mt5-small' ) A : int =tokenizer('Hello there' , return_tensors='pt' ).input_ids A : Union[str, Any] =tokenizer('Hi I am' , return_tensors='pt' ).input_ids A : Tuple =model(input_ids.to(_a ) , labels=labels.to(_a ) ).loss A : Optional[int] =-(labels.shape[-1] * loss.item()) A : Optional[int] =-8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
705
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
0
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowercase : Optional[Any] =logging.get_logger(__name__) _lowercase : Any ={'''vocab_file''': '''spiece.model'''} _lowercase : List[Any] ={ '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } _lowercase : Any ={ '''AI-Sweden/gpt-sw3-126m''': 2_0_4_8, '''AI-Sweden/gpt-sw3-350m''': 2_0_4_8, '''AI-Sweden/gpt-sw3-1.6b''': 2_0_4_8, '''AI-Sweden/gpt-sw3-6.7b''': 2_0_4_8, '''AI-Sweden/gpt-sw3-20b''': 2_0_4_8, } class SCREAMING_SNAKE_CASE_ ( __a ): '''simple docstring''' lowercase : List[str] = VOCAB_FILES_NAMES lowercase : int = PRETRAINED_VOCAB_FILES_MAP lowercase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Tuple: A : Union[str, Any] ={} if sp_model_kwargs is None else sp_model_kwargs A : Tuple =kwargs.get('name_or_path' ) if name_or_path is None: logger.warning( 'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,' ' you are testing the model, this can safely be ignored' ) A : str ="""None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing A : Tuple ="""<|endoftext|>""" if eos_token is None else eos_token A : str ="""<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: A : List[Any] =unk_token if pad_token is None else pad_token A : Union[str, Any] =eos_token if bos_token is None else bos_token else: A : str ="""<pad>""" if pad_token is None else pad_token A : List[str] ="""<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , pad_token=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) A : Dict =do_lower_case A : Any =remove_space A : Optional[int] =keep_accents A : Optional[int] =vocab_file A : Dict =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) # Used for whitespace normalization in input texts # fmt : off A : str ={""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing A : Union[str, Any] =re.compile( f'[{"".join(map(a_ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(1_27 , 1_60 ) ) + [1_60, 1_73, 82_03] ) )}]' ) def __getstate__( self : Any ) -> Any: A : Tuple =self.__dict__.copy() A : int =None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: A : Optional[Any] =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): A : Union[str, Any] ={} A : Union[str, Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: return len(self.sp_model ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : str ) -> Tuple: A : Dict =self.non_printing_characters_re.sub('' , a_ ) # Normalize whitespaces A : Any ="""""".join([char if char not in self.whitespaces else ' ' for char in text] ) # NFC Unicode normalization A : Optional[Any] =unicodedata.normalize('NFC' , a_ ) return text def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: A : Any =self.preprocess_text(a_ ) return self.sp_model.encode(a_ , out_type=a_ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str ) -> Dict: return self.sp_model.PieceToId(a_ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : int ) -> Dict: return self.sp_model.IdToPiece(a_ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return out_string def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : List[str] =[] A : Optional[Any] ="""""" A : Optional[int] =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(a_ ) + token A : int =True A : int =[] else: current_sub_tokens.append(a_ ) A : Union[str, Any] =False out_string += self.sp_model.decode(a_ ) return out_string def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: A : str ={self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Optional[Any]: if not os.path.isdir(a_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A : Optional[Any] =os.path.join( a_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , 'wb' ) as fi: A : Union[str, Any] =self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, List[str]] , SCREAMING_SNAKE_CASE__ : Union[str, bool] = False ) -> Tuple: if isinstance(a_ , a_ ): A : str =self.preprocess_text(a_ ) A : Optional[Any] =self.sp_model.encode(a_ ) else: A : int =[self.preprocess_text(a_ ) for t in text] A : List[Any] =self.sp_model.encode(a_ ) if return_tensors is True or return_tensors == "pt": A : List[str] =torch.tensor(a_ ) return token_ids def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[int, List[int]] ) -> Dict: return self.sp_model.decode(a_ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : "Conversation" ) -> Union[str, Any]: A : Union[str, Any] =[f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()] A : List[str] =( f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(a_ ) + f'{self.bos_token}Bot:' ) return self.encode(text=a_ )
706
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
0
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : str = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : str = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : Dict = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : List[str] = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : str = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : int = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Tuple = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : List[Any] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Dict = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
707
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowercase : Union[str, Any] =logging.get_logger(__name__) _lowercase : Union[str, Any] ="▁" _lowercase : str ={"vocab_file": "sentencepiece.bpe.model", "monolingual_vocab_file": "dict.txt"} _lowercase : Tuple ={ "vocab_file": { "vinai/bartpho-syllable": "https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model", }, "monolingual_vocab_file": { "vinai/bartpho-syllable": "https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt", }, } _lowercase : Optional[int] ={"vinai/bartpho-syllable": 1_0_2_4} class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase ): '''simple docstring''' lowercase : Optional[Any] = VOCAB_FILES_NAMES lowercase : Dict = PRETRAINED_VOCAB_FILES_MAP lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Tuple = ["input_ids", "attention_mask"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<s>" , SCREAMING_SNAKE_CASE__ : int="<unk>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[Any]="<mask>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> int: # Mask token behave like a normal word, i.e. include the space before it A : int =AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else mask_token A : Any ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , mask_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) A : Tuple =vocab_file A : Any =monolingual_vocab_file A : Optional[int] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowercase_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility A : Dict ={} A : Optional[int] =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(lowercase_ ) not in self.fairseq_tokens_to_ids: A : List[Any] =cnt cnt += 1 with open(lowercase_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): A : int =line.strip().split()[0] A : Dict =len(self.fairseq_tokens_to_ids ) if str(lowercase_ ) not in self.fairseq_tokens_to_ids: A : Optional[Any] =len(self.fairseq_tokens_to_ids ) A : Tuple ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : str ) -> Optional[Any]: A : List[str] =self.__dict__.copy() A : Optional[Any] =None A : str =self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : int =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): A : int ={} A : List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> Optional[Any]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A : Optional[int] =[self.cls_token_id] A : str =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> int: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_ ) if token_ids_a is None: return [1] + ([0] * len(lowercase_ )) + [1] return [1] + ([0] * len(lowercase_ )) + [1, 1] + ([0] * len(lowercase_ )) + [1] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[str]: A : Any =[self.sep_token_id] A : Tuple =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: return len(self.fairseq_ids_to_tokens ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: A : Dict ={self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> Any: return self.fairseq_ids_to_tokens[index] def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: A : Union[str, Any] ="""""".join(lowercase_ ).replace(lowercase_ , ' ' ).strip() return out_string def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Optional[int]: if not os.path.isdir(lowercase_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A : Optional[int] =os.path.join( lowercase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) A : str =os.path.join( lowercase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_ , 'wb' ) as fi: A : Optional[Any] =self.sp_model.serialized_model_proto() fi.write(lowercase_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( lowercase_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , lowercase_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(lowercase_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(lowercase_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
708
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
0
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _lowercase : str =get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right _lowercase : List[Any] =5_0_0_0_3 _lowercase : Union[str, Any] =5_0_0_0_2 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( a__ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = PLBartTokenizer lowercase : List[Any] = None lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : int ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =PLBartTokenizer(lowerCAmelCase__ , language_codes='base' , keep_accents=lowerCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: A : Optional[int] =PLBartTokenizer(lowerCAmelCase__ , language_codes='base' , keep_accents=lowerCAmelCase__ ) A : Optional[int] =tokenizer.tokenize('This is a test' ) self.assertListEqual(lowerCAmelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : List[Any] =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowerCAmelCase__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Union[str, Any] =tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) A : Tuple =tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ 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>', '.', ] , ) A : Optional[int] =tokenizer.vocab_size A : Any =[tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) for x in range(end - 4 , lowerCAmelCase__ )] self.assertListEqual(lowerCAmelCase__ , ['__java__', '__python__', '__en_XX__', '<mask>'] ) A : Any ="java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" A : Optional[int] =tokenizer(lowerCAmelCase__ ).input_ids self.assertEqual( tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ ) , lowerCAmelCase__ , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : Any =PLBartTokenizer(lowerCAmelCase__ , language_codes='multi' , keep_accents=lowerCAmelCase__ ) A : Dict =tokenizer.tokenize('This is a test' ) self.assertListEqual(lowerCAmelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : int =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowerCAmelCase__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : str =tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ 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>', '.', ] , ) A : Dict =tokenizer.vocab_size A : List[Any] =[tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) for x in range(end - 7 , lowerCAmelCase__ )] self.assertListEqual( lowerCAmelCase__ , ['__java__', '__python__', '__en_XX__', '__javascript__', '__php__', '__ruby__', '__go__'] ) A : List[str] ="java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" A : int =tokenizer(lowerCAmelCase__ ).input_ids self.assertEqual( tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ ) , lowerCAmelCase__ , ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : int = """uclanlp/plbart-python-en_XX""" lowercase : Tuple = [ """def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])""", """def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])""", ] lowercase : List[Any] = [ """Returns the maximum value of a b c.""", """Sums the values of a b c.""", ] lowercase : List[Any] = [ 134, 5452, 33460, 33441, 33463, 33465, 33463, 33449, 988, 20, 33456, 19, 33456, 771, 39, 4258, 889, 3318, 33441, 33463, 33465, 33463, 33449, 2471, 2, PYTHON_CODE, ] @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] ) -> List[Any]: A : PLBartTokenizer =PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes='base' , src_lang='python' , tgt_lang='en_XX' ) A : Optional[Any] =1 return cls def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__java__'] , 5_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__python__'] , 5_00_02 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__en_XX__'] , 5_00_03 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: A : List[str] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: self.assertIn(lowerCAmelCase__ , self.tokenizer.all_special_ids ) A : List[str] =[EN_CODE, 90_37, 3_34_42, 57, 7_52, 1_53, 14, 56, 18, 9, 2] A : List[Any] =self.tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) A : Dict =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase__ ) self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] =["def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])" * 20] self.assertIsInstance(src_text[0] , lowerCAmelCase__ ) A : Optional[Any] =10 A : Tuple =self.tokenizer(lowerCAmelCase__ , max_length=lowerCAmelCase__ , truncation=lowerCAmelCase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , lowerCAmelCase__ ) self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', '__java__'] ) , [5_00_04, 5_00_01] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : str =tempfile.mkdtemp() A : int =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowerCAmelCase__ ) A : List[str] =PLBartTokenizer.from_pretrained(lowerCAmelCase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowerCAmelCase__ ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : List[Any] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , return_tensors='pt' ) A : str =shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , lowerCAmelCase__ ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: A : Optional[int] =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) A : Optional[int] =shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertEqual((2, 26) , batch.input_ids.shape ) self.assertEqual((2, 26) , batch.attention_mask.shape ) A : Union[str, Any] =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Optional[Any] =self.tokenizer(self.src_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=3 , return_tensors='pt' ) A : List[str] =self.tokenizer( text_target=self.tgt_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=10 , return_tensors='pt' ) A : List[Any] =targets["input_ids"] A : Tuple =shift_tokens_right(lowerCAmelCase__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[Any]: A : List[Any] =self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='java' ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { # A, test, EOS, en_XX 'input_ids': [[1_50, 2_42, 2, 5_00_03]], 'attention_mask': [[1, 1, 1, 1]], # java 'forced_bos_token_id': 5_00_01, } , )
709
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, 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=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def A__ ( lowercase: str ) -> int: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : Tuple =create_tensor(UpperCAmelCase__ ) A : Optional[int] =gather(UpperCAmelCase__ ) assert gathered_tensor.tolist() == list(range(1, state.num_processes**2 + 1 ) ) def A__ ( lowercase: List[str] ) -> Optional[Any]: A : Optional[int] =[state.process_index] A : Union[str, Any] =gather_object(UpperCAmelCase__ ) assert len(UpperCAmelCase__ ) == state.num_processes, F'{gathered_obj}, {len(UpperCAmelCase__ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}' def A__ ( lowercase: str ) -> Union[str, Any]: A : str =create_tensor(UpperCAmelCase__ ) A : Optional[Any] =broadcast(UpperCAmelCase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1, state.num_processes + 1 ) ) def A__ ( lowercase: List[Any] ) -> List[str]: if state.is_main_process: A : List[str] =torch.arange(state.num_processes + 1 ).to(state.device ) else: A : Optional[Any] =torch.arange(state.num_processes ).to(state.device ) A : List[str] =pad_across_processes(UpperCAmelCase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0, state.num_processes ) ) + [0] def A__ ( lowercase: List[Any] ) -> Optional[int]: if state.num_processes != 2: return A : List[str] =create_tensor(UpperCAmelCase__ ) A : List[Any] =reduce(UpperCAmelCase__, 'sum' ) A : Optional[Any] =torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(UpperCAmelCase__, UpperCAmelCase__ ), F'{reduced_tensor} != {truth_tensor}' def A__ ( lowercase: Optional[Any] ) -> Dict: if state.num_processes != 2: return A : Optional[Any] =create_tensor(UpperCAmelCase__ ) A : Dict =reduce(UpperCAmelCase__, 'mean' ) A : Tuple =torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(UpperCAmelCase__, UpperCAmelCase__ ), F'{reduced_tensor} != {truth_tensor}' def A__ ( lowercase: Any ) -> str: main() def A__ ( ) -> Dict: A : Any =PartialState() state.print(F'State: {state}' ) state.print('testing gather' ) test_gather(UpperCAmelCase__ ) state.print('testing gather_object' ) test_gather_object(UpperCAmelCase__ ) state.print('testing broadcast' ) test_broadcast(UpperCAmelCase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(UpperCAmelCase__ ) state.print('testing reduce_sum' ) test_reduce_sum(UpperCAmelCase__ ) state.print('testing reduce_mean' ) test_reduce_mean(UpperCAmelCase__ ) if __name__ == "__main__": main()
710
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A : Optional[int] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : str =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : Optional[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A : Tuple ='base imports' if key == 'none' else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\n'.join(F'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
661
0
from __future__ import annotations def A__ ( lowercase: str, lowercase: Dict, lowercase: Optional[Any], ) -> str: if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif stress < 0: raise ValueError('Stress cannot be negative' ) elif tangential_force < 0: raise ValueError('Tangential Force cannot be negative' ) elif area < 0: raise ValueError('Area cannot be negative' ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
711
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase : str =logging.get_logger(__name__) _lowercase : int ={ 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class SCREAMING_SNAKE_CASE_ ( UpperCamelCase_ ): '''simple docstring''' lowercase : Any = "roformer" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[str]=5_00_00 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : int=7_68 , SCREAMING_SNAKE_CASE__ : Tuple=12 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_72 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Dict=15_36 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : List[str]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) A : Optional[int] =vocab_size A : Optional[Any] =hidden_size if embedding_size is None else embedding_size A : Union[str, Any] =hidden_size A : Any =num_hidden_layers A : Tuple =num_attention_heads A : Tuple =hidden_act A : Dict =intermediate_size A : Optional[Any] =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : str =max_position_embeddings A : Optional[Any] =type_vocab_size A : Optional[Any] =initializer_range A : Dict =layer_norm_eps A : List[Any] =rotary_value A : List[str] =use_cache class SCREAMING_SNAKE_CASE_ ( UpperCamelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: if self.task == "multiple-choice": A : str ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A : Dict ={0: '''batch''', 1: '''sequence'''} A : Union[str, Any] ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
712
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> str: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
0
import random def A__ ( lowercase: List[Any] ) -> bool: A : Dict =num - 1 A : List[Any] =0 while s % 2 == 0: A : Dict =s // 2 t += 1 for _ in range(5 ): A : List[str] =random.randrange(2, num - 1 ) A : List[Any] =pow(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase ) if v != 1: A : Tuple =0 while v != (num - 1): if i == t - 1: return False else: A : List[Any] =i + 1 A : Optional[int] =(v**2) % num return True def A__ ( lowercase: int ) -> bool: if num < 2: return False A : List[str] =[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__UpperCamelCase ) def A__ ( lowercase: Any = 1_024 ) -> int: while True: A : List[str] =random.randrange(2 ** (keysize - 1), 2 ** (keysize) ) if is_prime_low_num(__UpperCamelCase ): return num if __name__ == "__main__": _lowercase : Optional[Any] =generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
713
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : Union[str, Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Tuple, lowercase: Tuple = 16, lowercase: List[Any] = "bert-base-cased" ) -> Dict: A : Union[str, Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Optional[Any] ): # max_length=None => use the model max length (it's actually the default) A : Tuple =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : List[str] =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Dict =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : Tuple =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: int, lowercase: List[Any], lowercase: Optional[int], lowercase: List[str] ) -> Tuple: model.eval() A : str =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : int =model(**lowercase ) A : List[Any] =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A : int =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : Optional[int] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : str =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : str =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Dict, lowercase: Dict ) -> Union[str, Any]: # Initialize accelerator A : Union[str, Any] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : Optional[int] =config["""lr"""] A : Tuple =int(config['num_epochs'] ) A : Any =int(config['seed'] ) A : Tuple =int(config['batch_size'] ) A : int =args.model_name_or_path set_seed(lowercase ) A : Optional[int] =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[Any] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Dict =( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : Tuple =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Dict =accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: A : Optional[Any] =1 A : str =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : Any =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : Any =DummyScheduler(lowercase, total_num_steps=lowercase, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A : str =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : str =0 # We also need to keep track of the stating epoch so files are named properly A : int =0 A : int =evaluate.load('glue', 'mrpc' ) A : List[Any] =num_epochs if args.partial_train_epoch is not None: A : int =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : int =args.resume_from_checkpoint.split('epoch_' )[1] A : Optional[int] ="""""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : int =int(lowercase ) + 1 A : Dict =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : List[Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : Dict ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Union[str, Any] =model(**lowercase ) A : str =outputs.loss A : List[str] =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : int =F'epoch_{epoch}' A : Optional[int] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[int] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Optional[Any] =accuracy A : str =lr_scheduler.get_lr()[0] A : List[str] =optimizer.param_groups[0]["""lr"""] A : Union[str, Any] =epoch A : str =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Tuple: A : Tuple =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : List[str] =parser.parse_args() A : List[str] ={"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
714
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 ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =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] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
0
import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline _lowercase : int =argparse.ArgumentParser('''Stable Diffusion script with intel optimization''', add_help=False) parser.add_argument('''--dpm''', action='''store_true''', help='''Enable DPMSolver or not''') parser.add_argument('''--steps''', default=None, type=int, help='''Num inference steps''') _lowercase : Any =parser.parse_args() _lowercase : str ='''cpu''' _lowercase : Any ='''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings''' _lowercase : Dict ='''path-to-your-trained-model''' _lowercase : List[Any] =StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: _lowercase : Dict =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) _lowercase : List[str] =pipe.to(device) # to channels last _lowercase : Union[str, Any] =pipe.unet.to(memory_format=torch.channels_last) _lowercase : List[Any] =pipe.vae.to(memory_format=torch.channels_last) _lowercase : str =pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: _lowercase : Optional[Any] =pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex _lowercase : Optional[Any] =torch.randn(2, 4, 6_4, 6_4) _lowercase : str =torch.rand(1) * 9_9_9 _lowercase : Dict =torch.randn(2, 7_7, 7_6_8) _lowercase : str =(sample, timestep, encoder_hidden_status) try: _lowercase : Dict =ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: _lowercase : Optional[int] =ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) _lowercase : Tuple =ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) _lowercase : Tuple =ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: _lowercase : Any =ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute _lowercase : Any =6_6_6 _lowercase : Dict =torch.Generator(device).manual_seed(seed) _lowercase : Optional[int] ={'''generator''': generator} if args.steps is not None: _lowercase : List[Any] =args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): _lowercase : List[str] =pipe(prompt, **generate_kwargs).images[0] # save image image.save('''generated.png''')
715
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
0
def A__ ( ) -> Optional[Any]: '''simple docstring''' A : List[str] =[] A : Any =1 while len(_lowerCAmelCase ) < 1e6: constant.append(str(_lowerCAmelCase ) ) i += 1 A : Any ="".join(_lowerCAmelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9_999] ) * int(constant[99_999] ) * int(constant[999_999] ) ) if __name__ == "__main__": print(solution())
716
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
0
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 MobileViTImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Any=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : str=30 , SCREAMING_SNAKE_CASE__ : str=4_00 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , ) -> List[str]: A : Union[str, Any] =size if size is not None else {'shortest_edge': 20} A : Tuple =crop_size if crop_size is not None else {'height': 18, 'width': 18} A : Optional[Any] =parent A : str =batch_size A : Dict =num_channels A : str =image_size A : List[Any] =min_resolution A : List[str] =max_resolution A : Optional[Any] =do_resize A : Any =size A : List[Any] =do_center_crop A : Dict =crop_size A : str =do_flip_channel_order def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' lowercase : int = MobileViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> int: A : int =MobileViTImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[Any]: A : Dict =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_center_crop' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'center_crop' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_flip_channel_order' ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Dict =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) A : List[str] =self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[Any]: # Initialize image_processing A : int =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched A : str =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> str: # Initialize image_processing A : List[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Optional[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched A : List[str] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: # Initialize image_processing A : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Any =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched A : Optional[int] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
717
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
0
def A__ ( lowercase: str ) -> str: A : Tuple =[0] * len(__lowerCAmelCase ) A : Dict =[] A : Optional[Any] =[] A : Any =0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__lowerCAmelCase ) ): if indegree[i] == 0: queue.append(__lowerCAmelCase ) while queue: A : List[Any] =queue.pop(0 ) cnt += 1 topo.append(__lowerCAmelCase ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(__lowerCAmelCase ) if cnt != len(__lowerCAmelCase ): print('Cycle exists' ) else: print(__lowerCAmelCase ) # Adjacency List of Graph _lowercase : List[str] ={0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
718
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
0
from __future__ import annotations _lowercase : Dict =8.9_8_8E9 # units = N * m^s * C^-2 def A__ ( lowercase: Tuple, lowercase: Tuple, lowercase: Dict, lowercase: List[str] ) -> Optional[Any]: A : Optional[Any] =abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if distance < 0: raise ValueError('Distance cannot be negative' ) if force == 0: A : Optional[int] =COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: A : str =abs(lowercase__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: A : Tuple =abs(lowercase__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: A : List[str] =(COULOMBS_CONSTANT * charge_product / abs(lowercase__ )) ** 0.5 return {"distance": distance} raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
719
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
0
'''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_rembert import RemBertTokenizer else: _lowercase : Any =None _lowercase : List[Any] =logging.get_logger(__name__) _lowercase : int ={'vocab_file': 'sentencepiece.model', 'tokenizer_file': 'tokenizer.json'} _lowercase : int ={ 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, 'tokenizer_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/tokenizer.json', }, } _lowercase : Optional[Any] ={ 'google/rembert': 2_5_6, } _lowercase : Tuple ='▁' class SCREAMING_SNAKE_CASE_ ( __lowercase ): '''simple docstring''' lowercase : Optional[Any] = VOCAB_FILES_NAMES lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowercase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[int] = RemBertTokenizer def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Tuple="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="[SEP]" , SCREAMING_SNAKE_CASE__ : str="<pad>" , SCREAMING_SNAKE_CASE__ : str="[CLS]" , SCREAMING_SNAKE_CASE__ : List[str]="[MASK]" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[int]: # Mask token behave like a normal word, i.e. include the space before it A : Dict =AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , **__a , ) A : Optional[Any] =do_lower_case A : str =remove_space A : Any =keep_accents A : Optional[Any] =vocab_file A : Optional[int] =False if not self.vocab_file else True def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: A : Optional[Any] =[self.sep_token_id] A : Dict =[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 SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1] def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: A : Union[str, Any] =[self.sep_token_id] A : List[str] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__a ): logger.error('Vocabulary path ({}) should be a directory'.format(__a ) ) return A : Optional[Any] =os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ): copyfile(self.vocab_file , __a ) return (out_vocab_file,)
720
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
0
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=13 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str=99 , SCREAMING_SNAKE_CASE__ : List[Any]=32 , SCREAMING_SNAKE_CASE__ : int=5 , SCREAMING_SNAKE_CASE__ : Dict=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=37 , SCREAMING_SNAKE_CASE__ : Tuple="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=4 , SCREAMING_SNAKE_CASE__ : Tuple=None , ) -> int: A : Tuple =parent A : str =batch_size A : Any =seq_length A : List[str] =is_training A : List[str] =use_input_mask A : Union[str, Any] =use_token_type_ids A : List[Any] =use_labels A : Optional[Any] =vocab_size A : List[str] =hidden_size A : List[Any] =num_hidden_layers A : List[Any] =num_attention_heads A : List[Any] =intermediate_size A : Tuple =hidden_act A : Tuple =hidden_dropout_prob A : int =attention_probs_dropout_prob A : Optional[int] =max_position_embeddings A : int =type_vocab_size A : Tuple =type_sequence_label_size A : Optional[int] =initializer_range A : List[str] =num_labels A : Optional[int] =num_choices A : Optional[int] =scope def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: A : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict =None if self.use_input_mask: A : str =random_attention_mask([self.batch_size, self.seq_length] ) A : List[Any] =None if self.use_token_type_ids: A : int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : List[str] =None A : List[str] =None A : int =None if self.use_labels: A : Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Union[str, Any] =ids_tensor([self.batch_size] , self.num_choices ) A : str =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Union[str, Any]: return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: A : int =LlamaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) A : Optional[int] =model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , ) -> List[Any]: A : Dict =True A : Dict =LlamaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : List[Any] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A : Any =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) A : Any =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , ) -> Optional[int]: A : List[str] =LlamaForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : Tuple =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , ) -> Tuple: A : Any =True A : str =True A : str =LlamaForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # first forward pass A : Union[str, Any] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A : int =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : Optional[Any] =ids_tensor((self.batch_size, 3) , config.vocab_size ) A : List[Any] =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict =torch.cat([input_ids, next_tokens] , dim=-1 ) A : Any =torch.cat([input_mask, next_mask] , dim=-1 ) A : List[Any] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['hidden_states'][0] A : Union[str, Any] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['hidden_states'][0] # select random slice A : List[str] =ids_tensor((1,) , output_from_past.shape[-1] ).item() A : Optional[Any] =output_from_no_past[:, -3:, random_slice_idx].detach() A : Dict =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: A : Optional[Any] =self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) : List[str] =config_and_inputs A : Optional[int] ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Dict = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () lowercase : str = (LlamaForCausalLM,) if is_torch_available() else () lowercase : Optional[Any] = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) lowercase : str = False lowercase : str = False def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[int]: A : Any =LlamaModelTester(self ) A : Tuple =ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: A : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: A : List[Any] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A : int =type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: A , A : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() A : List[Any] =3 A : Tuple =input_dict['input_ids'] A : Any =input_ids.ne(1 ).to(UpperCAmelCase__ ) A : List[Any] =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A : Optional[int] =LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : List[str] =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: A , A : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() A : Union[str, Any] =3 A : Optional[Any] ='single_label_classification' A : Optional[Any] =input_dict['input_ids'] A : Optional[int] =input_ids.ne(1 ).to(UpperCAmelCase__ ) A : Any =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A : str =LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : List[Any] =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict: A , A : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() A : Union[str, Any] =3 A : Union[str, Any] ='multi_label_classification' A : List[Any] =input_dict['input_ids'] A : Optional[Any] =input_ids.ne(1 ).to(UpperCAmelCase__ ) A : Optional[Any] =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A : str =LlamaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() A : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[int]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> Tuple: A , A : Any =self.model_tester.prepare_config_and_inputs_for_common() A : List[Any] =ids_tensor([1, 10] , config.vocab_size ) A : Optional[int] =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A : Dict =LlamaModel(UpperCAmelCase__ ) original_model.to(UpperCAmelCase__ ) original_model.eval() A : List[str] =original_model(UpperCAmelCase__ ).last_hidden_state A : Optional[Any] =original_model(UpperCAmelCase__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A : Optional[int] ={'type': scaling_type, 'factor': 1_0.0} A : int =LlamaModel(UpperCAmelCase__ ) scaled_model.to(UpperCAmelCase__ ) scaled_model.eval() A : str =scaled_model(UpperCAmelCase__ ).last_hidden_state A : List[Any] =scaled_model(UpperCAmelCase__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-5 ) ) @require_torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: A : Optional[int] =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] A : List[Any] =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) A : Any =model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 A : Tuple =torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A : Optional[Any] =torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , UpperCAmelCase__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: A : Any =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] A : List[Any] =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) A : List[str] =model(torch.tensor(UpperCAmelCase__ ) ) # Expected mean on dim = -1 A : Union[str, Any] =torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A : Dict =torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , UpperCAmelCase__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: A : Optional[Any] =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] A : Dict =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) A : str =model(torch.tensor(UpperCAmelCase__ ) ) # Expected mean on dim = -1 A : Union[str, Any] =torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off A : Tuple =torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: A : str =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38] A : Tuple =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) A : List[Any] =model(torch.tensor(UpperCAmelCase__ ) ) A : Dict =torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , UpperCAmelCase__ , atol=1e-2 , rtol=1e-2 ) # fmt: off A : Tuple =torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , UpperCAmelCase__ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Dict ='Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' A : Any ='Simply put, the theory of relativity states that ' A : Dict =LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) A : Dict =tokenizer.encode(UpperCAmelCase__ , return_tensors='pt' ) A : Dict =LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=UpperCAmelCase__ ) # greedy generation outputs A : List[Any] =model.generate(UpperCAmelCase__ , max_new_tokens=64 , top_p=UpperCAmelCase__ , temperature=1 , do_sample=UpperCAmelCase__ ) A : Union[str, Any] =tokenizer.decode(generated_ids[0] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
721
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE_ ( __a , __a , unittest.TestCase ): '''simple docstring''' lowercase : int = StableDiffusionPanoramaPipeline lowercase : Tuple = TEXT_TO_IMAGE_PARAMS lowercase : str = TEXT_TO_IMAGE_BATCH_PARAMS lowercase : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: torch.manual_seed(0 ) A : int =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) A : List[Any] =DDIMScheduler() torch.manual_seed(0 ) A : Tuple =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) A : int =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) A : Tuple =CLIPTextModel(A__ ) A : Optional[Any] =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A : Tuple ={ 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=0 ) -> Optional[Any]: A : List[Any] =torch.manual_seed(A__ ) A : int ={ 'prompt': 'a photo of the dolomites', 'generator': generator, # Setting height and width to None to prevent OOMs on CPU. 'height': None, 'width': None, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[str]: A : List[str] ='cpu' # ensure determinism for the device-dependent torch.Generator A : List[str] =self.get_dummy_components() A : str =StableDiffusionPanoramaPipeline(**A__ ) A : int =sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A : List[str] =self.get_dummy_inputs(A__ ) A : str =sd_pipe(**A__ ).images A : int =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : Union[str, Any] =np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Union[str, Any]: A : int ='cpu' # ensure determinism for the device-dependent torch.Generator A : Optional[Any] =self.get_dummy_components() A : List[Any] =StableDiffusionPanoramaPipeline(**A__ ) A : List[Any] =sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A : int =self.get_dummy_inputs(A__ ) A : Optional[int] ='french fries' A : List[Any] =sd_pipe(**A__ , negative_prompt=A__ ) A : Any =output.images A : Union[str, Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : str =np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> str: A : str ='cpu' # ensure determinism for the device-dependent torch.Generator A : List[str] =self.get_dummy_components() A : int =StableDiffusionPanoramaPipeline(**A__ ) A : Any =sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A : Tuple =self.get_dummy_inputs(A__ ) A : int =sd_pipe(**A__ , view_batch_size=2 ) A : int =output.images A : Union[str, Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : Dict =np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: A : Dict ='cpu' # ensure determinism for the device-dependent torch.Generator A : Any =self.get_dummy_components() A : str =EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' ) A : Any =StableDiffusionPanoramaPipeline(**A__ ) A : Dict =sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A : Tuple =self.get_dummy_inputs(A__ ) A : List[Any] =sd_pipe(**A__ ).images A : Optional[int] =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : Optional[int] =np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: A : Optional[int] ='cpu' # ensure determinism for the device-dependent torch.Generator A : Union[str, Any] =self.get_dummy_components() A : Dict =PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , skip_prk_steps=A__ ) A : Tuple =StableDiffusionPanoramaPipeline(**A__ ) A : List[str] =sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) A : List[Any] =self.get_dummy_inputs(A__ ) A : Optional[int] =sd_pipe(**A__ ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : Union[str, Any] =np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 ) -> str: A : Optional[int] =torch.manual_seed(A__ ) A : List[Any] ={ 'prompt': 'a photo of the dolomites', 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : List[Any] ='stabilityai/stable-diffusion-2-base' A : Union[str, Any] =DDIMScheduler.from_pretrained(A__ , subfolder='scheduler' ) A : Optional[Any] =StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() A : int =self.get_inputs() A : str =pipe(**A__ ).images A : Optional[int] =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) A : List[Any] =np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : int =StableDiffusionPanoramaPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-base' , safety_checker=A__ ) A : int =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() A : List[str] =self.get_inputs() A : str =pipe(**A__ ).images A : str =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) A : Tuple =np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: A : Union[str, Any] =0 def callback_fn(SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any ) -> None: A : Any =True nonlocal number_of_steps number_of_steps += 1 if step == 1: A : Any =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) A : Optional[Any] =latents[0, -3:, -3:, -1] A : Tuple =np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: A : Dict =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) A : Optional[Any] =latents[0, -3:, -3:, -1] A : Tuple =np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 A : Any =False A : Optional[Any] ='stabilityai/stable-diffusion-2-base' A : int =DDIMScheduler.from_pretrained(A__ , subfolder='scheduler' ) A : List[str] =StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) A : Dict =pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() A : str =self.get_inputs() pipe(**A__ , callback=A__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() A : Union[str, Any] ='stabilityai/stable-diffusion-2-base' A : Optional[Any] =DDIMScheduler.from_pretrained(A__ , subfolder='scheduler' ) A : Any =StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) A : Optional[int] =pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() A : Union[str, Any] =self.get_inputs() A : List[Any] =pipe(**A__ ) A : int =torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
700
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
0
class SCREAMING_SNAKE_CASE_ : # Public class to implement a graph '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[bool]] ) -> None: A : str =row A : List[str] =col A : int =graph def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[bool]] ) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[bool]] ) -> None: A : Any =[-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A : Union[str, Any] =[-1, 0, 1, -1, 1, -1, 0, 1] A : Union[str, Any] =True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE__ ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: # And finally, count all islands. A : Any =[[False for j in range(self.COL )] for i in range(self.ROW )] A : Dict =0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += 1 return count
701
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
0
def A__ ( lowercase: Dict ) -> List[str]: for i in range(len(lowercase__ ) - 1, 0, -1 ): A : Optional[Any] =False for j in range(lowercase__, 0, -1 ): if unsorted[j] < unsorted[j - 1]: A , A : Tuple =unsorted[j - 1], unsorted[j] A : Any =True for j in range(lowercase__ ): if unsorted[j] > unsorted[j + 1]: A , A : Dict =unsorted[j + 1], unsorted[j] A : Union[str, Any] =True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() _lowercase : Union[str, Any] =input('''Enter numbers separated by a comma:\n''').strip() _lowercase : str =[int(item) for item in user_input.split(''',''')] print(f'''{cocktail_shaker_sort(unsorted) = }''')
702
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
0
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed _lowercase : Dict ='true' def A__ ( lowercase: str, lowercase: int=82, lowercase: Union[str, Any]=16 ) -> List[Any]: set_seed(42 ) A : List[Any] =RegressionModel() A : int =deepcopy(lowerCAmelCase_ ) A : Optional[int] =RegressionDataset(length=lowerCAmelCase_ ) A : Optional[Any] =DataLoader(lowerCAmelCase_, batch_size=lowerCAmelCase_ ) model.to(accelerator.device ) A : str =accelerator.prepare(lowerCAmelCase_, lowerCAmelCase_ ) return model, ddp_model, dataloader def A__ ( lowercase: str, lowercase: Any=False ) -> Optional[int]: A : Any =AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' ) A : str =load_dataset('glue', 'mrpc', split='validation' ) def tokenize_function(lowercase: Tuple ): A : str =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs with accelerator.main_process_first(): A : int =dataset.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) A : Any =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: List[str] ): if use_longest: return tokenizer.pad(lowerCAmelCase_, padding='longest', return_tensors='pt' ) return tokenizer.pad(lowerCAmelCase_, padding='max_length', max_length=128, return_tensors='pt' ) return DataLoader(lowerCAmelCase_, shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=16 ) def A__ ( lowercase: Tuple, lowercase: Union[str, Any] ) -> Optional[Any]: A : List[Any] =Accelerator(dispatch_batches=lowerCAmelCase_, split_batches=lowerCAmelCase_ ) A : Dict =get_dataloader(lowerCAmelCase_, not dispatch_batches ) A : List[Any] =AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased', return_dict=lowerCAmelCase_ ) A : Tuple =accelerator.prepare(lowerCAmelCase_, lowerCAmelCase_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def A__ ( lowercase: int, lowercase: Optional[int], lowercase: Dict ) -> Optional[int]: A : str =[] for batch in dataloader: A : int =batch.values() with torch.no_grad(): A : List[str] =model(lowerCAmelCase_ ) A : Optional[int] =accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) A : Union[str, Any] =[], [] for logit, targ in logits_and_targets: logits.append(lowerCAmelCase_ ) targs.append(lowerCAmelCase_ ) A : Optional[int] =torch.cat(lowerCAmelCase_ ), torch.cat(lowerCAmelCase_ ) return logits, targs def A__ ( lowercase: Any, lowercase: Any=82, lowercase: Optional[int]=False, lowercase: str=False, lowercase: str=16 ) -> str: A : Optional[Any] =get_basic_setup(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) A : Optional[int] =generate_predictions(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) assert ( len(lowerCAmelCase_ ) == num_samples ), F'Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(lowerCAmelCase_ )}' def A__ ( lowercase: int = False, lowercase: Any = False ) -> List[Any]: A : Any =evaluate.load('glue', 'mrpc' ) A : List[str] =get_mrpc_setup(lowerCAmelCase_, lowerCAmelCase_ ) # First do baseline A : List[Any] =setup['''no'''] model.to(lowerCAmelCase_ ) model.eval() for batch in dataloader: batch.to(lowerCAmelCase_ ) with torch.inference_mode(): A : Optional[Any] =model(**lowerCAmelCase_ ) A : Tuple =outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=lowerCAmelCase_, references=batch['labels'] ) A : Optional[int] =metric.compute() # Then do distributed A : Any =setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): A : Dict =model(**lowerCAmelCase_ ) A : Tuple =outputs.logits.argmax(dim=-1 ) A : Union[str, Any] =batch['''labels'''] A : Optional[Any] =accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=lowerCAmelCase_, references=lowerCAmelCase_ ) A : Optional[int] =metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key], distributed[key] ), F'Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n' def A__ ( ) -> Any: A : List[str] =Accelerator(split_batches=lowerCAmelCase_, dispatch_batches=lowerCAmelCase_ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`' ) test_mrpc(lowerCAmelCase_, lowerCAmelCase_ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: A : List[Any] =Accelerator(split_batches=lowerCAmelCase_, dispatch_batches=lowerCAmelCase_ ) if accelerator.is_local_main_process: print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99' ) test_torch_metrics(lowerCAmelCase_, 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**' ) A : Optional[int] =Accelerator() test_torch_metrics(lowerCAmelCase_, 512 ) accelerator.state._reset_state() def A__ ( lowercase: List[Any] ) -> Optional[int]: main() if __name__ == "__main__": main()
703
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
0
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' lowercase : Tuple = ["""onnx"""] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: requires_backends(self , ['onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Dict , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: requires_backends(cls , ['onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: requires_backends(cls , ['onnx'] )
704
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
0
from itertools import product def A__ ( lowercase: int, lowercase: int ) -> Union[str, Any]: A : List[Any] =sides_number A : List[Any] =max_face_number * dice_number A : Dict =[0] * (max_total + 1) A : Tuple =1 A : Dict =range(a_, max_face_number + 1 ) for dice_numbers in product(a_, repeat=a_ ): A : Optional[Any] =sum(a_ ) totals_frequencies[total] += 1 return totals_frequencies def A__ ( ) -> Tuple: A : int =total_frequency_distribution( sides_number=4, dice_number=9 ) A : Any =total_frequency_distribution( sides_number=6, dice_number=6 ) A : Optional[int] =0 A : Union[str, Any] =9 A : List[Any] =4 * 9 A : List[Any] =6 for peter_total in range(a_, max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) A : Union[str, Any] =(4**9) * (6**6) A : Tuple =peter_wins_count / total_games_number A : Optional[int] =round(a_, ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(f'''{solution() = }''')
705
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase : Tuple ={ """configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""], """tokenization_perceiver""": ["""PerceiverTokenizer"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Union[str, Any] =["""PerceiverFeatureExtractor"""] _lowercase : Optional[int] =["""PerceiverImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int =[ """PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PerceiverForImageClassificationConvProcessing""", """PerceiverForImageClassificationFourier""", """PerceiverForImageClassificationLearned""", """PerceiverForMaskedLM""", """PerceiverForMultimodalAutoencoding""", """PerceiverForOpticalFlow""", """PerceiverForSequenceClassification""", """PerceiverLayer""", """PerceiverModel""", """PerceiverPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
706
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
0
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: A : str =nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: A : List[str] =hidden_states.shape A : Dict =jax.image.resize( __a , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) A : Tuple =self.conv(__a ) return hidden_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[Any] =nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Any: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) A : Union[str, Any] =self.conv(__a ) return hidden_states class SCREAMING_SNAKE_CASE_ ( nn.Module ): '''simple docstring''' lowercase : int lowercase : int = None lowercase : float = 0.0 lowercase : bool = None lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> int: A : List[str] =self.in_channels if self.out_channels is None else self.out_channels A : int =nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) A : List[str] =nn.Conv( __a , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) A : Union[str, Any] =nn.Dense(__a , dtype=self.dtype ) A : Union[str, Any] =nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) A : Dict =nn.Dropout(self.dropout_prob ) A : List[str] =nn.Conv( __a , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) A : Optional[Any] =self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut A : List[str] =None if use_nin_shortcut: A : List[Any] =nn.Conv( __a , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any=True ) -> Dict: A : Optional[int] =hidden_states A : List[Any] =self.norma(__a ) A : Any =nn.swish(__a ) A : str =self.conva(__a ) A : Any =self.time_emb_proj(nn.swish(__a ) ) A : Any =jnp.expand_dims(jnp.expand_dims(__a , 1 ) , 1 ) A : str =hidden_states + temb A : Any =self.norma(__a ) A : Optional[Any] =nn.swish(__a ) A : Optional[Any] =self.dropout(__a , __a ) A : List[str] =self.conva(__a ) if self.conv_shortcut is not None: A : str =self.conv_shortcut(__a ) return hidden_states + residual
707
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : 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 : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsé.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
0