code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch __lowercase : List[str] = random.Random() def lowercase_ ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ) -> Union[str, Any]: '''simple docstring''' if rng is None: lowerCamelCase_ : Optional[Any] = global_rng lowerCamelCase_ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowercase ( unittest.TestCase ): def __init__(self , A , A=7 , A=4_0_0 , A=2_0_0_0 , A=1_0 , A=1_6_0 , A=8 , A=0.0 , A=4_0_0_0 , A=False , A=True , ): lowerCamelCase_ : Optional[Any] = parent lowerCamelCase_ : Optional[Any] = batch_size lowerCamelCase_ : Any = min_seq_length lowerCamelCase_ : str = max_seq_length lowerCamelCase_ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCamelCase_ : Optional[Any] = padding_value lowerCamelCase_ : Any = sampling_rate lowerCamelCase_ : Tuple = return_attention_mask lowerCamelCase_ : List[str] = do_normalize lowerCamelCase_ : Dict = feature_size lowerCamelCase_ : Optional[int] = chunk_length lowerCamelCase_ : Union[str, Any] = hop_length def UpperCAmelCase__ (self ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ (self , A=False , A=False ): def _flatten(A ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: lowerCamelCase_ : Optional[int] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCamelCase_ : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCamelCase_ : Optional[Any] = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowercase ( _lowerCAmelCase , unittest.TestCase ): lowerCamelCase : List[Any] = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ (self ): lowerCamelCase_ : Dict = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ (self ): lowerCamelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ : Optional[Any] = feat_extract_first.save_pretrained(_lowerCamelCase )[0] check_json_file_has_correct_format(_lowerCamelCase ) lowerCamelCase_ : Tuple = self.feature_extraction_class.from_pretrained(_lowerCamelCase ) lowerCamelCase_ : List[Any] = feat_extract_first.to_dict() lowerCamelCase_ : Dict = feat_extract_second.to_dict() lowerCamelCase_ : Optional[Any] = feat_extract_first.mel_filters lowerCamelCase_ : List[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase__ (self ): lowerCamelCase_ : int = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ : List[Any] = os.path.join(_lowerCamelCase , '''feat_extract.json''' ) feat_extract_first.to_json_file(_lowerCamelCase ) lowerCamelCase_ : Optional[Any] = self.feature_extraction_class.from_json_file(_lowerCamelCase ) lowerCamelCase_ : List[str] = feat_extract_first.to_dict() lowerCamelCase_ : int = feat_extract_second.to_dict() lowerCamelCase_ : Tuple = feat_extract_first.mel_filters lowerCamelCase_ : List[str] = feat_extract_second.mel_filters self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase__ (self ): lowerCamelCase_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCamelCase_ : List[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase_ : Optional[int] = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test feature size lowerCamelCase_ : Tuple = feature_extractor(_lowerCamelCase , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input lowerCamelCase_ : Optional[int] = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features lowerCamelCase_ : Optional[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 ) ) # Test batched lowerCamelCase_ : str = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features lowerCamelCase_ : Optional[Any] = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_lowerCamelCase , _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. lowerCamelCase_ : Tuple = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] lowerCamelCase_ : str = np.asarray(_lowerCamelCase ) lowerCamelCase_ : Union[str, Any] = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features lowerCamelCase_ : List[Any] = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_lowerCamelCase , _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 ) ) # Test truncation required lowerCamelCase_ : List[Any] = [floats_list((1, x) )[0] for x in range(2_0_0 , (feature_extractor.n_samples + 5_0_0) , 2_0_0 )] lowerCamelCase_ : List[str] = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] lowerCamelCase_ : str = [x[: feature_extractor.n_samples] for x in speech_inputs] lowerCamelCase_ : Union[str, Any] = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs_truncated] lowerCamelCase_ : Tuple = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features lowerCamelCase_ : str = feature_extractor(_lowerCamelCase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_lowerCamelCase , _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 ) ) def UpperCAmelCase__ (self ): import torch lowerCamelCase_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase_ : Union[str, Any] = np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) lowerCamelCase_ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCamelCase_ : Dict = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) lowerCamelCase_ : Any = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ (self , A ): lowerCamelCase_ : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech lowerCamelCase_ : Optional[Any] = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def UpperCAmelCase__ (self ): lowerCamelCase_ : Any = torch.tensor( [ 0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51, 0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78, 0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54, -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54 ] ) # fmt: on lowerCamelCase_ : Optional[int] = self._load_datasamples(1 ) lowerCamelCase_ : str = WhisperFeatureExtractor() lowerCamelCase_ : str = feature_extractor(_lowerCamelCase , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 8_0, 3_0_0_0) ) self.assertTrue(torch.allclose(input_features[0, 0, :3_0] , _lowerCamelCase , atol=1E-4 ) ) def UpperCAmelCase__ (self ): lowerCamelCase_ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase_ : Dict = self._load_datasamples(1 )[0] lowerCamelCase_ : str = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5 # Rescale to [0, 65535] to show issue lowerCamelCase_ : Union[str, Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=_lowerCamelCase )[0] self.assertTrue(np.all(np.mean(_lowerCamelCase ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(_lowerCamelCase ) - 1 ) < 1E-3 ) )
318
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
from __future__ import annotations import math class lowercase : def __init__( self ,A__): lowercase = size # approximate the overall size of segment tree with given value lowercase = [0 for i in range(0 ,4 * size)] # create array to store lazy update lowercase = [0 for i in range(0 ,4 * size)] lowercase = [0 for i in range(0 ,4 * size)] # flag for lazy update def A__ ( self ,A__): return idx * 2 def A__ ( self ,A__): return idx * 2 + 1 def A__ ( self ,A__ ,A__ ,A__ ,A__): if left_element == right_element: lowercase = a[left_element - 1] else: lowercase = (left_element + right_element) // 2 self.build(self.left(_lowerCamelCase) ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) self.build(self.right(_lowerCamelCase) ,mid + 1 ,_lowerCamelCase ,_lowerCamelCase) lowercase = max( self.segment_tree[self.left(_lowerCamelCase)] ,self.segment_tree[self.right(_lowerCamelCase)]) def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__): if self.flag[idx] is True: lowercase = self.lazy[idx] lowercase = False if left_element != right_element: lowercase = self.lazy[idx] lowercase = self.lazy[idx] lowercase = True lowercase = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: lowercase = val if left_element != right_element: lowercase = val lowercase = val lowercase = True lowercase = True return True lowercase = (left_element + right_element) // 2 self.update(self.left(_lowerCamelCase) ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) self.update(self.right(_lowerCamelCase) ,mid + 1 ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) lowercase = max( self.segment_tree[self.left(_lowerCamelCase)] ,self.segment_tree[self.right(_lowerCamelCase)]) return True def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__): if self.flag[idx] is True: lowercase = self.lazy[idx] lowercase = False if left_element != right_element: lowercase = self.lazy[idx] lowercase = self.lazy[idx] lowercase = True lowercase = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] lowercase = (left_element + right_element) // 2 lowercase = self.query(self.left(_lowerCamelCase) ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) lowercase = self.query(self.right(_lowerCamelCase) ,mid + 1 ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) return max(_lowerCamelCase ,_lowerCamelCase) def __str__( self): return str([self.query(1 ,1 ,self.size ,_lowerCamelCase ,_lowerCamelCase) for i in range(1 ,self.size + 1)]) if __name__ == "__main__": lowercase__ :int = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] lowercase__ :Tuple = 15 lowercase__ :int = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE_ : int = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextConfig', 'Pix2StructVisionConfig', ], 'processing_pix2struct': ['Pix2StructProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ : Dict = ['Pix2StructImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ : Optional[Any] = [ 'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Pix2StructPreTrainedModel', 'Pix2StructForConditionalGeneration', 'Pix2StructVisionModel', 'Pix2StructTextModel', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys SCREAMING_SNAKE_CASE_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
335
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''apply_ocr''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'''height''': 42, '''width''': 42} ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) self.assertIsInstance(encoding.words, _lowerCamelCase ) self.assertIsInstance(encoding.boxes, _lowerCamelCase ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : List[Any] = logging.get_logger(__name__) lowercase : int = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class __UpperCAmelCase ( _lowerCAmelCase ): __lowercase = "xmod" def __init__( self , lowerCAmelCase_=3_05_22 , lowerCAmelCase_=7_68 , lowerCAmelCase_=12 , lowerCAmelCase_=12 , lowerCAmelCase_=30_72 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=1E-12 , lowerCAmelCase_=1 , lowerCAmelCase_=0 , lowerCAmelCase_=2 , lowerCAmelCase_="absolute" , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=2 , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=("en_XX",) , lowerCAmelCase_=None , **lowerCAmelCase_ , ): """simple docstring""" super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = hidden_act _snake_case = intermediate_size _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = initializer_range _snake_case = layer_norm_eps _snake_case = position_embedding_type _snake_case = use_cache _snake_case = classifier_dropout _snake_case = pre_norm _snake_case = adapter_reduction_factor _snake_case = adapter_layer_norm _snake_case = adapter_reuse_layer_norm _snake_case = ln_before_adapter _snake_case = list(_lowerCamelCase ) _snake_case = default_language class __UpperCAmelCase ( _lowerCAmelCase ): @property def lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": _snake_case = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _snake_case = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
42
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a : Union[str, Any] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( _lowercase : str ) ->Any: '''simple docstring''' print("Loading config file..." ) def flatten_yaml_as_dict(_lowercase : str , _lowercase : Tuple="" , _lowercase : Optional[int]="." ): a : Union[str, Any] = [] for k, v in d.items(): a : str = parent_key + sep + k if parent_key else k if isinstance(__UpperCamelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(__UpperCamelCase , __UpperCamelCase , sep=__UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(__UpperCamelCase ) a : Optional[int] = argparse.Namespace() with open(__UpperCamelCase , "r" ) as yaml_file: try: a : Optional[int] = yaml.load(__UpperCamelCase , Loader=yaml.FullLoader ) a : str = flatten_yaml_as_dict(__UpperCamelCase ) for k, v in flat_cfg.items(): setattr(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) except yaml.YAMLError as exc: logger.error("Error while loading config file: {}. Error message: {}".format(__UpperCamelCase , str(__UpperCamelCase ) ) ) return config def _SCREAMING_SNAKE_CASE ( _lowercase : Optional[int] , _lowercase : Dict ) ->Tuple: '''simple docstring''' a : Optional[Any] = MobileViTVaConfig() a : Dict = False # dataset if task_name.startswith("imagenet1k_" ): a : str = 1000 if int(task_name.strip().split("_" )[-1] ) == 384: a : Optional[int] = 384 else: a : Union[str, Any] = 256 a : Optional[int] = "imagenet-1k-id2label.json" elif task_name.startswith("imagenet21k_to_1k_" ): a : Optional[Any] = 2_1000 if int(task_name.strip().split("_" )[-1] ) == 384: a : Optional[int] = 384 else: a : List[Any] = 256 a : List[str] = "imagenet-22k-id2label.json" elif task_name.startswith("ade20k_" ): a : Dict = 151 a : Any = 512 a : Union[str, Any] = "ade20k-id2label.json" a : Dict = True elif task_name.startswith("voc_" ): a : Tuple = 21 a : Union[str, Any] = 512 a : List[Any] = "pascal-voc-id2label.json" a : Optional[Any] = True # orig_config a : Tuple = load_orig_config_file(__UpperCamelCase ) assert getattr(__UpperCamelCase , "model.classification.name" , -1 ) == "mobilevit_v2", "Invalid model" a : List[str] = getattr(__UpperCamelCase , "model.classification.mitv2.width_multiplier" , 1.0 ) assert ( getattr(__UpperCamelCase , "model.classification.mitv2.attn_norm_layer" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" a : Tuple = getattr(__UpperCamelCase , "model.classification.activation.name" , "swish" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: a : List[str] = getattr(__UpperCamelCase , "model.segmentation.output_stride" , 16 ) if "_deeplabv3" in task_name: a : List[str] = getattr(__UpperCamelCase , "model.segmentation.deeplabv3.aspp_rates" , [12, 24, 36] ) a : Optional[int] = getattr(__UpperCamelCase , "model.segmentation.deeplabv3.aspp_out_channels" , 512 ) a : str = getattr(__UpperCamelCase , "model.segmentation.deeplabv3.aspp_dropout" , 0.1 ) # id2label a : Optional[int] = "huggingface/label-files" a : Union[str, Any] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type="dataset" ) , "r" ) ) a : Any = {int(__UpperCamelCase ): v for k, v in idalabel.items()} a : Union[str, Any] = idalabel a : Union[str, Any] = {v: k for k, v in idalabel.items()} return config def _SCREAMING_SNAKE_CASE ( _lowercase : int , _lowercase : Optional[Any] , _lowercase : Tuple ) ->Union[str, Any]: '''simple docstring''' a : List[Any] = dct.pop(__UpperCamelCase ) a : Tuple = val def _SCREAMING_SNAKE_CASE ( _lowercase : int , _lowercase : Union[str, Any]=False ) ->List[Any]: '''simple docstring''' if base_model: a : Dict = "" else: a : Tuple = "mobilevitv2." a : Tuple = [] for k in state_dict.keys(): if k[:8] == "encoder.": a : int = k[8:] else: a : Any = k if ".block." in k: a : List[Any] = k_new.replace(".block." , "." ) if ".conv." in k: a : List[str] = k_new.replace(".conv." , ".convolution." ) if ".norm." in k: a : Tuple = k_new.replace(".norm." , ".normalization." ) if "conv_1." in k: a : Union[str, Any] = k_new.replace("conv_1." , F"""{model_prefix}conv_stem.""" ) for i in [1, 2]: if F"""layer_{i}.""" in k: a : Any = k_new.replace(F"""layer_{i}.""" , F"""{model_prefix}encoder.layer.{i-1}.layer.""" ) if ".exp_1x1." in k: a : int = k_new.replace(".exp_1x1." , ".expand_1x1." ) if ".red_1x1." in k: a : Optional[Any] = k_new.replace(".red_1x1." , ".reduce_1x1." ) for i in [3, 4, 5]: if F"""layer_{i}.0.""" in k: a : int = k_new.replace(F"""layer_{i}.0.""" , F"""{model_prefix}encoder.layer.{i-1}.downsampling_layer.""" ) if F"""layer_{i}.1.local_rep.0.""" in k: a : Dict = k_new.replace(F"""layer_{i}.1.local_rep.0.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_kxk.""" ) if F"""layer_{i}.1.local_rep.1.""" in k: a : Tuple = k_new.replace(F"""layer_{i}.1.local_rep.1.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_1x1.""" ) for i in [3, 4, 5]: if i == 3: a : Tuple = [0, 1] elif i == 4: a : Tuple = [0, 1, 2, 3] elif i == 5: a : Union[str, Any] = [0, 1, 2] for j in j_in: if F"""layer_{i}.1.global_rep.{j}.""" in k: a : str = k_new.replace( F"""layer_{i}.1.global_rep.{j}.""" , F"""{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.""" ) if F"""layer_{i}.1.global_rep.{j+1}.""" in k: a : Dict = k_new.replace( F"""layer_{i}.1.global_rep.{j+1}.""" , F"""{model_prefix}encoder.layer.{i-1}.layernorm.""" ) if F"""layer_{i}.1.conv_proj.""" in k: a : Optional[Any] = k_new.replace(F"""layer_{i}.1.conv_proj.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_projection.""" ) if "pre_norm_attn.0." in k: a : Dict = k_new.replace("pre_norm_attn.0." , "layernorm_before." ) if "pre_norm_attn.1." in k: a : Tuple = k_new.replace("pre_norm_attn.1." , "attention." ) if "pre_norm_ffn.0." in k: a : Optional[Any] = k_new.replace("pre_norm_ffn.0." , "layernorm_after." ) if "pre_norm_ffn.1." in k: a : Dict = k_new.replace("pre_norm_ffn.1." , "ffn.conv1." ) if "pre_norm_ffn.3." in k: a : str = k_new.replace("pre_norm_ffn.3." , "ffn.conv2." ) if "classifier.1." in k: a : int = k_new.replace("classifier.1." , "classifier." ) if "seg_head." in k: a : Any = k_new.replace("seg_head." , "segmentation_head." ) if ".aspp_layer." in k: a : Dict = k_new.replace(".aspp_layer." , "." ) if ".aspp_pool." in k: a : Dict = k_new.replace(".aspp_pool." , "." ) rename_keys.append((k, k_new) ) return rename_keys def _SCREAMING_SNAKE_CASE ( _lowercase : Dict ) ->List[Any]: '''simple docstring''' a : Optional[Any] = [] for k in state_dict.keys(): if k.startswith("seg_head.aux_head." ): keys_to_ignore.append(__UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def _SCREAMING_SNAKE_CASE ( ) ->Any: '''simple docstring''' a : Any = "http://images.cocodataset.org/val2017/000000039769.jpg" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" a : List[Any] = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def _SCREAMING_SNAKE_CASE ( _lowercase : Any , _lowercase : int , _lowercase : Any , _lowercase : Dict ) ->Any: '''simple docstring''' a : Tuple = get_mobilevitva_config(__UpperCamelCase , __UpperCamelCase ) # load original state_dict a : List[str] = torch.load(__UpperCamelCase , map_location="cpu" ) # load huggingface model if task_name.startswith("ade20k_" ) or task_name.startswith("voc_" ): a : Optional[int] = MobileViTVaForSemanticSegmentation(__UpperCamelCase ).eval() a : List[str] = False else: a : Union[str, Any] = MobileViTVaForImageClassification(__UpperCamelCase ).eval() a : Union[str, Any] = False # remove and rename some keys of load the original model a : List[str] = checkpoint remove_unused_keys(__UpperCamelCase ) a : List[Any] = create_rename_keys(__UpperCamelCase , base_model=__UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # load modified state_dict model.load_state_dict(__UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor a : Union[str, Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) a : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) a : str = model(**__UpperCamelCase ) # verify classification model if task_name.startswith("imagenet" ): a : Tuple = outputs.logits a : int = logits.argmax(-1 ).item() print("Predicted class:" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("imagenet1k_256" ) and config.width_multiplier == 1.0: # expected_logits for base variant a : Union[str, Any] = torch.tensor([-1.6_3_3_6E0_0, -7.3_2_0_4E-0_2, -5.1_8_8_3E-0_1] ) assert torch.allclose(logits[0, :3] , __UpperCamelCase , atol=1E-4 ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(F"""Saving model {task_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": a : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' '''\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) a : int = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
105
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE () -> Dict: """simple docstring""" for n in range(1 , 1_000_000 ): yield n * (n + 1) // 2 def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = 1 lowercase__ = 2 while i * i <= n: lowercase__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _SCREAMING_SNAKE_CASE () -> Dict: """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(__UpperCamelCase ) > 500 ) if __name__ == "__main__": print(solution())
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__UpperCamelCase )] ) SCREAMING_SNAKE_CASE__ : int = np.array(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() ,__UpperCamelCase ) ) ,x.transpose() ) ,__UpperCamelCase ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = (1, 2, 1) SCREAMING_SNAKE_CASE__ : List[str] = (1, 1, 0, 7) SCREAMING_SNAKE_CASE__ : List[Any] = SARIMAX( __UpperCamelCase ,exog=__UpperCamelCase ,order=__UpperCamelCase ,seasonal_order=__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Any = model.fit(disp=__UpperCamelCase ,maxiter=600 ,method="""nm""" ) SCREAMING_SNAKE_CASE__ : List[Any] = model_fit.predict(1 ,len(__UpperCamelCase ) ,exog=[test_match] ) return result[0] def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : int = SVR(kernel="""rbf""" ,C=1 ,gamma=0.1 ,epsilon=0.1 ) regressor.fit(__UpperCamelCase ,__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = regressor.predict(__UpperCamelCase ) return y_pred[0] def lowercase_ ( _snake_case ): train_user.sort() SCREAMING_SNAKE_CASE__ : Any = np.percentile(__UpperCamelCase ,25 ) SCREAMING_SNAKE_CASE__ : str = np.percentile(__UpperCamelCase ,75 ) SCREAMING_SNAKE_CASE__ : List[Any] = qa - qa SCREAMING_SNAKE_CASE__ : Optional[Any] = qa - (iqr * 0.1) return low_lim def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = 0 for i in list_vote: if i > actual_result: SCREAMING_SNAKE_CASE__ : Optional[int] = not_safe + 1 else: if abs(abs(__UpperCamelCase ) - abs(__UpperCamelCase ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) UpperCAmelCase__ : str = [[1_8_2_3_1, 0.0, 1], [2_2_6_2_1, 1.0, 2], [1_5_6_7_5, 0.0, 3], [2_3_5_8_3, 1.0, 4]] UpperCAmelCase__ : int = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) UpperCAmelCase__ : Tuple = Normalizer().fit_transform(data_input_df.values) # split data UpperCAmelCase__ : Optional[Any] = normalize_df[:, 2].tolist() UpperCAmelCase__ : Union[str, Any] = normalize_df[:, 0].tolist() UpperCAmelCase__ : int = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) UpperCAmelCase__ : Any = normalize_df[:, [1, 2]].tolist() UpperCAmelCase__ : int = x[: len(x) - 1] UpperCAmelCase__ : Union[str, Any] = x[len(x) - 1 :] # for linear regression & sarimax UpperCAmelCase__ : Optional[int] = total_date[: len(total_date) - 1] UpperCAmelCase__ : Any = total_user[: len(total_user) - 1] UpperCAmelCase__ : Optional[Any] = total_match[: len(total_match) - 1] UpperCAmelCase__ : Dict = total_date[len(total_date) - 1 :] UpperCAmelCase__ : str = total_user[len(total_user) - 1 :] UpperCAmelCase__ : Optional[int] = total_match[len(total_match) - 1 :] # voting system with forecasting UpperCAmelCase__ : Optional[Any] = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data UpperCAmelCase__ : int = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
25
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
import os import platform import sys lowerCamelCase_ = '''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
244
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from statistics import mean, stdev def __lowerCamelCase ( A__ , A__ = 3 ) -> Optional[int]: """simple docstring""" UpperCamelCase = min(__UpperCamelCase ) UpperCamelCase = max(__UpperCamelCase ) # normalize data return [round((x - x_min) / (x_max - x_min) , __UpperCamelCase ) for x in data] def __lowerCamelCase ( A__ , A__ = 3 ) -> Tuple: """simple docstring""" UpperCamelCase = mean(__UpperCamelCase ) UpperCamelCase = stdev(__UpperCamelCase ) # standardize data return [round((x - mu) / (sigma) , __UpperCamelCase ) for x in data]
28
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Any = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): lowerCAmelCase__ : Optional[Any] = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: lowerCAmelCase__ : str = column continue lowerCAmelCase__ : Optional[int] = column / magnitude # Subtract to cancel term lowerCAmelCase__ : Union[str, Any] = current_set[0] lowerCAmelCase__ : str = [first_row] lowerCAmelCase__ : str = current_set[1::] for row in current_set: lowerCAmelCase__ : Dict = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: lowerCAmelCase__ : List[str] = final_set[0] lowerCAmelCase__ : Optional[int] = [] lowerCAmelCase__ : Any = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) lowerCAmelCase__ : List[Any] = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) lowerCAmelCase__ : List[Any] = resultant return final_set def __SCREAMING_SNAKE_CASE ( A_ ): if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) lowerCAmelCase__ : str = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] lowerCAmelCase__ : List[str] = equations.copy() if any(0 in row for row in data_set ): lowerCAmelCase__ : int = data_set.copy() lowerCAmelCase__ : Tuple = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: lowerCAmelCase__ : List[str] = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) lowerCAmelCase__ : str = data_set.copy() lowerCAmelCase__ : List[str] = simplify(__UpperCamelCase ) lowerCAmelCase__ : Optional[int] = simplified[::-1] lowerCAmelCase__ : Tuple = [] for row in simplified: lowerCAmelCase__ : List[str] = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue lowerCAmelCase__ : Any = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue lowerCAmelCase__ : List[str] = temp_row[1::] lowerCAmelCase__ : Optional[int] = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) lowerCAmelCase__ : List[Any] = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : List[str] = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
def __lowercase ( lowerCamelCase : int ): if num < 0: return False UpperCamelCase_ : int = num UpperCamelCase_ : Any = 0 while num > 0: UpperCamelCase_ : Union[str, Any] = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
175
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) __A = 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 : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' import datasets from .evaluate import evaluate __lowercase : Optional[int] = '''\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n''' __lowercase : Optional[Any] = '''\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n''' __lowercase : Union[str, Any] = '''\nComputes SQuAD scores (F1 and EM).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': the text of the answer\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the SQuAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\nExamples:\n\n >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> squad_metric = datasets.load_metric("squad")\n >>> results = squad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0}\n''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowercase ( datasets.Metric ): def UpperCAmelCase__ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': {'''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.Value('''string''' )}, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , ) def UpperCAmelCase__ (self , A , A ): lowerCamelCase_ : List[Any] = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} lowerCamelCase_ : Any = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] lowerCamelCase_ : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
318
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise TypeError('''only integers accepted as input''' ) else: lowercase = str(abs(__UpperCamelCase ) ) lowercase = [list(__UpperCamelCase ) for char in range(len(__UpperCamelCase ) )] for index in range(len(__UpperCamelCase ) ): num_transpositions[index].pop(__UpperCamelCase ) return max( int(''''''.join(list(__UpperCamelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
101
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" import numpy # List of input, output pairs SCREAMING_SNAKE_CASE_ : Optional[Any] = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) SCREAMING_SNAKE_CASE_ : Optional[int] = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) SCREAMING_SNAKE_CASE_ : List[str] = [2, 4, 1, 5] SCREAMING_SNAKE_CASE_ : List[Any] = len(train_data) SCREAMING_SNAKE_CASE_ : int = 0.009 def _snake_case ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any]="train" ): return calculate_hypothesis_value(__UpperCamelCase , __UpperCamelCase ) - output( __UpperCamelCase , __UpperCamelCase ) def _snake_case ( UpperCAmelCase_ : Union[str, Any] ): A__ = 0 for i in range(len(__UpperCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _snake_case ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str] ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : Dict ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _snake_case ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict=m ): A__ = 0 for i in range(__UpperCamelCase ): if index == -1: summation_value += _error(__UpperCamelCase ) else: summation_value += _error(__UpperCamelCase ) * train_data[i][0][index] return summation_value def _snake_case ( UpperCAmelCase_ : Tuple ): A__ = summation_of_cost_derivative(__UpperCamelCase , __UpperCamelCase ) / m return cost_derivative_value def _snake_case ( ): global parameter_vector # Tune these values to set a tolerance value for predicted output A__ = 0.00_00_02 A__ = 0 A__ = 0 while True: j += 1 A__ = [0, 0, 0, 0] for i in range(0 , len(__UpperCamelCase ) ): A__ = get_cost_derivative(i - 1 ) A__ = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( __UpperCamelCase , __UpperCamelCase , atol=__UpperCamelCase , rtol=__UpperCamelCase , ): break A__ = temp_parameter_vector print(("""Number of iterations:""", j) ) def _snake_case ( ): for i in range(len(__UpperCamelCase ) ): print(("""Actual output value:""", output(__UpperCamelCase , """test""" )) ) print(("""Hypothesis output:""", calculate_hypothesis_value(__UpperCamelCase , """test""" )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
335
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowercase : Tuple = logging.get_logger(__name__) lowercase : Dict = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowercase : str = { "vocab_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json" }, "merges_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt" }, } lowercase : Any = {"allegro/herbert-base-cased": 514} lowercase : str = {} class __UpperCAmelCase ( _lowerCAmelCase ): __lowercase = VOCAB_FILES_NAMES __lowercase = PRETRAINED_VOCAB_FILES_MAP __lowercase = PRETRAINED_INIT_CONFIGURATION __lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase = HerbertTokenizer def __init__( self , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_="<s>" , lowerCAmelCase_="<unk>" , lowerCAmelCase_="<pad>" , lowerCAmelCase_="<mask>" , lowerCAmelCase_="</s>" , **lowerCAmelCase_ , ): """simple docstring""" super().__init__( _lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sep_token=_lowerCamelCase , **_lowerCamelCase , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = None ): """simple docstring""" _snake_case = [self.cls_token_id] _snake_case = [self.sep_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 lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = None ): """simple docstring""" _snake_case = [self.sep_token_id] _snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = None ): """simple docstring""" _snake_case = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
42
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""simple docstring""" import os def _SCREAMING_SNAKE_CASE ( ) ->Optional[int]: '''simple docstring''' a : str = os.path.join(os.path.dirname(__UpperCamelCase ) , "num.txt" ) with open(__UpperCamelCase ) as file_hand: return str(sum(int(__UpperCamelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
105
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else mask_token super().__init__( errors=_lowerCamelCase, bos_token=_lowerCamelCase, eos_token=_lowerCamelCase, unk_token=_lowerCamelCase, sep_token=_lowerCamelCase, cls_token=_lowerCamelCase, pad_token=_lowerCamelCase, mask_token=_lowerCamelCase, add_prefix_space=_lowerCamelCase, **_lowerCamelCase, ) with open(_lowerCamelCase, encoding='''utf-8''' ) as vocab_handle: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = j if word[i] == first and i < len(_lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase ).split(''' ''' ) ) return bpe_tokens def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=_lowerCamelCase, ensure_ascii=_lowerCamelCase ) + '''\n''' ) __A = 0 with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda _lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase, token_ids_a=_lowerCamelCase, already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1] def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = kwargs.pop('''add_prefix_space''', self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase ) > 0 and not text[0].isspace()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowerCamelCase : List[str] = logging.get_logger(__name__) class __lowerCAmelCase (_lowerCAmelCase ): '''simple docstring''' def __init__(self : Optional[int] , *UpperCamelCase : Union[str, Any] , **UpperCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
2
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
"""simple docstring""" import operator as op def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = lambda _snake_case ,_snake_case : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE__ : str = { """^""": op.pow, """*""": op.mul, """/""": div, """+""": op.add, """-""": op.sub, } # operators & their respective operation # print table header print("""Symbol""".center(8 ) ,"""Action""".center(12 ) ,"""Stack""" ,sep=""" | """ ) print("""-""" * (30 + len(__UpperCamelCase )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__UpperCamelCase ) # append x to stack # output in tabular format print(x.rjust(8 ) ,("""push(""" + x + """)""").ljust(12 ) ,""",""".join(__UpperCamelCase ) ,sep=""" | """ ) else: SCREAMING_SNAKE_CASE__ : Any = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) ,("""pop(""" + b + """)""").ljust(12 ) ,""",""".join(__UpperCamelCase ) ,sep=""" | """ ) SCREAMING_SNAKE_CASE__ : List[Any] = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) ,("""pop(""" + a + """)""").ljust(12 ) ,""",""".join(__UpperCamelCase ) ,sep=""" | """ ) stack.append( str(opr[x](int(__UpperCamelCase ) ,int(__UpperCamelCase ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) ,("""push(""" + a + x + b + """)""").ljust(12 ) ,""",""".join(__UpperCamelCase ) ,sep=""" | """ ,) return int(stack[0] ) if __name__ == "__main__": UpperCAmelCase__ : Any = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ') print('\n\tResult = ', solve(Postfix))
25
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
import math def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' if not isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase__ = f"Input value of [number={number}] must be an integer" raise TypeError(__UpperCamelCase ) if number < 1: UpperCamelCase__ = f"Input value of [number={number}] must be > 0" raise ValueError(__UpperCamelCase ) elif number == 1: return 3 elif number == 2: return 5 else: UpperCamelCase__ = int(math.log(number // 3 , 2 ) ) + 2 UpperCamelCase__ = [3, 5] UpperCamelCase__ = 2 UpperCamelCase__ = 3 for block in range(1 , __UpperCamelCase ): for _ in range(__UpperCamelCase ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): lowerCamelCase_ = 0 try: lowerCamelCase_ = proth(number) except ValueError: print(f'ValueError: there is no {number}th Proth number') continue print(f'The {number}th Proth number: {value}')
244
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase, model_name='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
'''simple docstring''' def __lowerCamelCase ( A__ ) -> Dict: """simple docstring""" try: UpperCamelCase = float(__UpperCamelCase ) except ValueError: raise ValueError('Please enter a valid number' ) UpperCamelCase = decimal - int(__UpperCamelCase ) if fractional_part == 0: return int(__UpperCamelCase ), 1 else: UpperCamelCase = len(str(__UpperCamelCase ).split('.' )[1] ) UpperCamelCase = int(decimal * (10**number_of_frac_digits) ) UpperCamelCase = 10**number_of_frac_digits UpperCamelCase , UpperCamelCase = denominator, numerator while True: UpperCamelCase = dividend % divisor if remainder == 0: break UpperCamelCase , UpperCamelCase = divisor, remainder UpperCamelCase , UpperCamelCase = numerator / divisor, denominator / divisor return int(__UpperCamelCase ), int(__UpperCamelCase ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction('67') = }''') print(f'''{decimal_to_fraction('45.0') = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction('6.25') = }''') print(f'''{decimal_to_fraction('78td') = }''')
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, 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 ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Optional[Any] ,lowercase_ : List[str] ,lowercase_ : List[str]=1_3 ,lowercase_ : Union[str, Any]=7 ,lowercase_ : Tuple=True ,lowercase_ : List[str]=True ,lowercase_ : Union[str, Any]=True ,lowercase_ : List[str]=True ,lowercase_ : Tuple=9_9 ,lowercase_ : Optional[Any]=3_2 ,lowercase_ : Optional[int]=2 ,lowercase_ : Optional[Any]=4 ,lowercase_ : int=3_7 ,lowercase_ : Dict="gelu" ,lowercase_ : str=0.1 ,lowercase_ : str=0.1 ,lowercase_ : Dict=5_1_2 ,lowercase_ : Optional[Any]=1_6 ,lowercase_ : Optional[Any]=2 ,lowercase_ : int=0.02 ,lowercase_ : Optional[Any]=False ,lowercase_ : List[Any]=True ,lowercase_ : Optional[Any]="None" ,lowercase_ : int=3 ,lowercase_ : int=4 ,lowercase_ : Union[str, Any]=None ,): lowerCAmelCase__ : int = parent lowerCAmelCase__ : Optional[int] = batch_size lowerCAmelCase__ : Optional[Any] = seq_length lowerCAmelCase__ : Optional[Any] = is_training lowerCAmelCase__ : Dict = use_input_mask lowerCAmelCase__ : str = use_token_type_ids lowerCAmelCase__ : str = use_labels lowerCAmelCase__ : Any = vocab_size lowerCAmelCase__ : Optional[int] = hidden_size lowerCAmelCase__ : Any = num_hidden_layers lowerCAmelCase__ : Optional[Any] = num_attention_heads lowerCAmelCase__ : List[str] = intermediate_size lowerCAmelCase__ : List[Any] = hidden_act lowerCAmelCase__ : Tuple = hidden_dropout_prob lowerCAmelCase__ : List[Any] = attention_probs_dropout_prob lowerCAmelCase__ : List[str] = max_position_embeddings lowerCAmelCase__ : List[Any] = type_vocab_size lowerCAmelCase__ : int = type_sequence_label_size lowerCAmelCase__ : List[Any] = initializer_range lowerCAmelCase__ : List[Any] = num_labels lowerCAmelCase__ : Union[str, Any] = num_choices lowerCAmelCase__ : int = relative_attention lowerCAmelCase__ : str = position_biased_input lowerCAmelCase__ : Optional[Any] = pos_att_type lowerCAmelCase__ : Tuple = scope def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowerCAmelCase__ : Tuple = None if self.use_input_mask: lowerCAmelCase__ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ : Any = None if self.use_token_type_ids: lowerCAmelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowerCAmelCase__ : Optional[Any] = None lowerCAmelCase__ : List[Any] = None lowerCAmelCase__ : Any = None if self.use_labels: lowerCAmelCase__ : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowerCAmelCase__ : str = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowerCAmelCase__ : int = DebertaVaConfig( 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 ,relative_attention=self.relative_attention ,position_biased_input=self.position_biased_input ,initializer_range=self.initializer_range ,return_dict=_lowerCamelCase ,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : Dict ,lowercase_ : Union[str, Any] ,lowercase_ : Any ,lowercase_ : Optional[int] ,lowercase_ : str ,lowercase_ : Optional[int] ,lowercase_ : Tuple ,lowercase_ : List[str] ): lowerCAmelCase__ : Optional[int] = TFDebertaVaModel(config=_lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCAmelCase__ : Any = [input_ids, input_mask] lowerCAmelCase__ : List[Any] = model(_lowerCamelCase ) lowerCAmelCase__ : str = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : int ,lowercase_ : int ,lowercase_ : Union[str, Any] ,lowercase_ : Tuple ,lowercase_ : Optional[Any] ,lowercase_ : Optional[int] ,lowercase_ : int ,lowercase_ : Optional[int] ): lowerCAmelCase__ : Tuple = TFDebertaVaForMaskedLM(config=_lowerCamelCase ) lowerCAmelCase__ : Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Dict = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Any ,lowercase_ : Optional[int] ,lowercase_ : Union[str, Any] ,lowercase_ : Union[str, Any] ,lowercase_ : Tuple ,lowercase_ : Any ,lowercase_ : Optional[int] ,lowercase_ : Any ): lowerCAmelCase__ : List[str] = self.num_labels lowerCAmelCase__ : List[str] = TFDebertaVaForSequenceClassification(config=_lowerCamelCase ) lowerCAmelCase__ : Optional[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Tuple = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : str ,lowercase_ : List[Any] ,lowercase_ : Any ,lowercase_ : Union[str, Any] ,lowercase_ : int ,lowercase_ : Tuple ,lowercase_ : Optional[int] ): lowerCAmelCase__ : Dict = self.num_labels lowerCAmelCase__ : Optional[int] = TFDebertaVaForTokenClassification(config=_lowerCamelCase ) lowerCAmelCase__ : Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : int = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] ,lowercase_ : Optional[int] ,lowercase_ : str ,lowercase_ : Optional[int] ,lowercase_ : Dict ,lowercase_ : Union[str, Any] ,lowercase_ : int ,lowercase_ : List[str] ): lowerCAmelCase__ : Tuple = TFDebertaVaForQuestionAnswering(config=_lowerCamelCase ) lowerCAmelCase__ : List[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Tuple = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) : List[str] = config_and_inputs lowerCAmelCase__ : 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__ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) lowercase__ = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) lowercase__ = False lowercase__ = False def __lowerCAmelCase ( self : Any ): lowerCAmelCase__ : Optional[int] = TFDebertaVaModelTester(self ) lowerCAmelCase__ : Dict = ConfigTester(self ,config_class=_lowerCamelCase ,hidden_size=3_7 ) def __lowerCAmelCase ( self : Dict ): self.config_tester.run_common_tests() def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : List[Any] = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_lowerCamelCase ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason='''Model not available yet''' ) def __lowerCAmelCase ( self : int ): pass @slow def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : str = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) lowerCAmelCase__ : Optional[int] = tf.constant([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) lowerCAmelCase__ : str = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) lowerCAmelCase__ : List[str] = model(_lowerCamelCase ,attention_mask=_lowerCamelCase )[0] lowerCAmelCase__ : Any = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] ,_lowerCamelCase ,atol=1E-4 )
106
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' from __future__ import annotations import requests __lowercase : Union[str, Any] = set( '''approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'''.split() ) def lowercase_ ( _lowercase , _lowercase = 1 , _lowercase = "new" , _lowercase = None ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ : Dict = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(__UpperCamelCase ) - valid_terms ) ): lowerCamelCase_ : List[str] = F"""Invalid search term: {invalid_search_terms}""" raise ValueError(__UpperCamelCase ) lowerCamelCase_ : Optional[Any] = requests.get( F"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError lowerCamelCase_ : Dict = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(__UpperCamelCase )} lowerCamelCase_ : List[str] = {} for id_ in range(__UpperCamelCase ): lowerCamelCase_ : Optional[int] = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('''learnpython''', wanted_data=['''title''', '''url''', '''selftext''']))
318
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' if ( (cp >= 0x4e00 and cp <= 0x9fff) or (cp >= 0x3400 and cp <= 0x4dbf) # or (cp >= 0x20000 and cp <= 0x2a6df) # or (cp >= 0x2a700 and cp <= 0x2b73f) # or (cp >= 0x2b740 and cp <= 0x2b81f) # or (cp >= 0x2b820 and cp <= 0x2ceaf) # or (cp >= 0xf900 and cp <= 0xfaff) or (cp >= 0x2f800 and cp <= 0x2fa1f) # ): # return True return False def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' for char in word: lowercase = ord(__UpperCamelCase ) if not _is_chinese_char(__UpperCamelCase ): return 0 return 1 def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = set() for token in tokens: lowercase = len(__UpperCamelCase ) > 1 and is_chinese(__UpperCamelCase ) if chinese_word: word_set.add(__UpperCamelCase ) lowercase = list(__UpperCamelCase ) return word_list def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' if not chinese_word_set: return bert_tokens lowercase = max([len(__UpperCamelCase ) for w in chinese_word_set] ) lowercase = bert_tokens lowercase , lowercase = 0, len(__UpperCamelCase ) while start < end: lowercase = True if is_chinese(bert_word[start] ): lowercase = min(end - start , __UpperCamelCase ) for i in range(__UpperCamelCase , 1 , -1 ): lowercase = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): lowercase = '''##''' + bert_word[j] lowercase = start + i lowercase = False break if single_word: start += 1 return bert_word def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = [] for i in range(0 , len(__UpperCamelCase ) , 100 ): lowercase = ltp_tokenizer.seg(lines[i : i + 100] )[0] lowercase = [get_chinese_word(__UpperCamelCase ) for r in res] ltp_res.extend(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) lowercase = [] for i in range(0 , len(__UpperCamelCase ) , 100 ): lowercase = bert_tokenizer(lines[i : i + 100] , add_special_tokens=__UpperCamelCase , truncation=__UpperCamelCase , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) lowercase = [] for input_ids, chinese_word in zip(__UpperCamelCase , __UpperCamelCase ): lowercase = [] for id in input_ids: lowercase = bert_tokenizer._convert_id_to_token(__UpperCamelCase ) input_tokens.append(__UpperCamelCase ) lowercase = add_sub_symbol(__UpperCamelCase , __UpperCamelCase ) lowercase = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__UpperCamelCase ): if token[:2] == "##": lowercase = token[2:] # save chinese tokens' pos if len(__UpperCamelCase ) == 1 and _is_chinese_char(ord(__UpperCamelCase ) ): ref_id.append(__UpperCamelCase ) ref_ids.append(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) return ref_ids def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: lowercase = f.readlines() lowercase = [line.strip() for line in data if len(__UpperCamelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' lowercase = LTP(args.ltp ) # faster in GPU device lowercase = BertTokenizer.from_pretrained(args.bert ) lowercase = prepare_ref(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: lowercase = [json.dumps(__UpperCamelCase ) + '''\n''' for ref in ref_ids] f.writelines(__UpperCamelCase ) if __name__ == "__main__": lowercase__ :List[Any] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path" ) parser.add_argument("--bert", type=str, default="./resources/robert", help="resources for Bert tokenizer") parser.add_argument("--save_path", type=str, default="./resources/ref.txt", help="path to save res") lowercase__ :Optional[int] = parser.parse_args() main(args)
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" from string import ascii_uppercase SCREAMING_SNAKE_CASE_ : Tuple = {char: i for i, char in enumerate(ascii_uppercase)} SCREAMING_SNAKE_CASE_ : List[str] = dict(enumerate(ascii_uppercase)) def _snake_case ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Any ): A__ = len(__UpperCamelCase ) A__ = 0 while True: if x == i: A__ = 0 if len(__UpperCamelCase ) == len(__UpperCamelCase ): break key += key[i] i += 1 return key def _snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] ): A__ = """""" A__ = 0 for letter in message: if letter == " ": cipher_text += " " else: A__ = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] ): A__ = """""" A__ = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A__ = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A__ = """THE GERMAN ATTACK""" A__ = """SECRET""" A__ = generate_key(__UpperCamelCase , __UpperCamelCase ) A__ = cipher_text(__UpperCamelCase , __UpperCamelCase ) print(F"""Encrypted Text = {s}""" ) print(F"""Original Text = {original_text(__UpperCamelCase , __UpperCamelCase )}""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
335
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''apply_ocr''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'''height''': 42, '''width''': 42} ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) self.assertIsInstance(encoding.words, _lowerCamelCase ) self.assertIsInstance(encoding.boxes, _lowerCamelCase ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __UpperCAmelCase ( unittest.TestCase ): def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=3 , lowerCAmelCase_=2_24 , lowerCAmelCase_=30 , lowerCAmelCase_=4_00 , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=True , lowerCAmelCase_=[0.5, 0.5, 0.5] , lowerCAmelCase_=[0.5, 0.5, 0.5] , ): """simple docstring""" _snake_case = size if size is not None else {'height': 18, 'width': 18} _snake_case = parent _snake_case = batch_size _snake_case = num_channels _snake_case = image_size _snake_case = min_resolution _snake_case = max_resolution _snake_case = do_resize _snake_case = size _snake_case = do_normalize _snake_case = image_mean _snake_case = image_std def lowerCamelCase ( self ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __UpperCAmelCase ( _lowerCAmelCase , unittest.TestCase ): __lowercase = ViTImageProcessor if is_vision_available() else None def lowerCamelCase ( self ): """simple docstring""" _snake_case = EfficientFormerImageProcessorTester(self ) @property def lowerCamelCase ( self ): """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , 'image_mean' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'image_std' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'do_normalize' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'do_resize' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'size' ) ) def lowerCamelCase ( self ): """simple docstring""" pass def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _snake_case = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input _snake_case = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched _snake_case = image_processor(_lowerCamelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , )
42
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a : int = logging.get_logger(__name__) a : Optional[Any] = { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/config.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/config.json''' # See all FNet models at https://huggingface.co/models?filter=fnet } class __UpperCamelCase ( _lowerCAmelCase ): lowerCamelCase : Dict ="fnet" def __init__( self , lowerCAmelCase__=3_2000 , lowerCAmelCase__=768 , lowerCAmelCase__=12 , lowerCAmelCase__=3072 , lowerCAmelCase__="gelu_new" , lowerCAmelCase__=0.1 , lowerCAmelCase__=512 , lowerCAmelCase__=4 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=False , lowerCAmelCase__=512 , lowerCAmelCase__=3 , lowerCAmelCase__=1 , lowerCAmelCase__=2 , **lowerCAmelCase__ , ) -> Tuple: super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) a : Dict = vocab_size a : List[Any] = max_position_embeddings a : Optional[int] = hidden_size a : str = num_hidden_layers a : List[Any] = intermediate_size a : Union[str, Any] = hidden_act a : List[Any] = hidden_dropout_prob a : str = initializer_range a : Any = type_vocab_size a : Optional[int] = layer_norm_eps a : List[str] = use_tpu_fourier_optimizations a : Any = tpu_short_seq_length
105
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel 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 UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase (_lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = DanceDiffusionPipeline lowerCAmelCase__ : List[Any] = UNCONDITIONAL_AUDIO_GENERATION_PARAMS lowerCAmelCase__ : int = PipelineTesterMixin.required_optional_params - { "callback", "latents", "callback_steps", "output_type", "num_images_per_prompt", } lowerCAmelCase__ : Tuple = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS lowerCAmelCase__ : Dict = False lowerCAmelCase__ : Optional[int] = False def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = UNetaDModel( block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=16000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=_lowerCamelCase , use_timestep_embedding=_lowerCamelCase , time_embedding_type='''fourier''' , mid_block_type='''UNetMidBlock1D''' , down_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''') , up_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''') , ) lowercase__ = IPNDMScheduler() lowercase__ = { '''unet''': unet, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : str=0 ): '''simple docstring''' if str(_lowerCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(_lowerCamelCase ) else: lowercase__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) lowercase__ = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 4, } return inputs def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowercase__ = self.get_dummy_components() lowercase__ = DanceDiffusionPipeline(**_lowerCamelCase ) lowercase__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowercase__ = self.get_dummy_inputs(_lowerCamelCase ) lowercase__ = pipe(**_lowerCamelCase ) lowercase__ = output.audios lowercase__ = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) lowercase__ = np.array([-0.72_65, 1.00_00, -0.83_88, 0.11_75, 0.94_98, -1.00_00] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' return super().test_save_load_local() @skip_mps def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) @skip_mps def UpperCamelCase__ (self : List[str] ): '''simple docstring''' return super().test_save_load_optional_components() @skip_mps def UpperCamelCase__ (self : Dict ): '''simple docstring''' return super().test_attention_slicing_forward_pass() def UpperCamelCase__ (self : str ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Any ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = torch_device lowercase__ = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k''' ) lowercase__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowercase__ = torch.manual_seed(0 ) lowercase__ = pipe(generator=_lowerCamelCase , num_inference_steps=100 , audio_length_in_s=4.0_96 ) lowercase__ = output.audios lowercase__ = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowercase__ = np.array([-0.01_92, -0.02_31, -0.03_18, -0.00_59, 0.00_02, -0.00_20] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = torch_device lowercase__ = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k''' , torch_dtype=torch.floataa ) lowercase__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowercase__ = torch.manual_seed(0 ) lowercase__ = pipe(generator=_lowerCamelCase , num_inference_steps=100 , audio_length_in_s=4.0_96 ) lowercase__ = output.audios lowercase__ = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowercase__ = np.array([-0.03_67, -0.04_88, -0.07_71, -0.05_25, -0.04_44, -0.03_41] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1E-2
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : str = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys UpperCAmelCase__ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
25
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable 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 .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
244
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def A ( self : List[str] ): """simple docstring""" UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = BlipImageProcessor() UpperCamelCase = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) UpperCamelCase = BlipaProcessor(_lowerCamelCase , _lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def A ( self : Tuple , **UpperCamelCase__ : List[Any] ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ).tokenizer def A ( self : Union[str, Any] , **UpperCamelCase__ : str ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ).image_processor def A ( self : Optional[Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def A ( self : int ): """simple docstring""" UpperCamelCase = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] UpperCamelCase = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def A ( self : List[str] ): """simple docstring""" UpperCamelCase = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) UpperCamelCase = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) UpperCamelCase = BlipaProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = BlipaProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = image_processor(_lowerCamelCase , return_tensors='np' ) UpperCamelCase = processor(images=_lowerCamelCase , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def A ( self : Tuple ): """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = BlipaProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) UpperCamelCase = 'lower newer' UpperCamelCase = processor(text=_lowerCamelCase ) UpperCamelCase = tokenizer(_lowerCamelCase , return_token_type_ids=_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A ( self : str ): """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = BlipaProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) UpperCamelCase = 'lower newer' UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(_lowerCamelCase ): processor() def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = BlipaProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase = processor.batch_decode(_lowerCamelCase ) UpperCamelCase = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = BlipaProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) UpperCamelCase = 'lower newer' UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = processor(text=_lowerCamelCase , images=_lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
28
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): lowerCAmelCase__ : Dict = len(__UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = [[0] * n for i in range(__UpperCamelCase )] for i in range(__UpperCamelCase ): lowerCAmelCase__ : int = y_points[i] for i in range(2 , __UpperCamelCase ): for j in range(__UpperCamelCase , __UpperCamelCase ): lowerCAmelCase__ : str = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable a_ = { 'configuration_gpt_neox_japanese': ['GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXJapaneseConfig'], 'tokenization_gpt_neox_japanese': ['GPTNeoXJapaneseTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXJapaneseForCausalLM', 'GPTNeoXJapaneseLayer', 'GPTNeoXJapaneseModel', 'GPTNeoXJapanesePreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
175
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) __A = 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 : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' import enum import shutil import sys __lowercase , __lowercase : Optional[Any] = shutil.get_terminal_size() __lowercase : List[Any] = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''} class __lowercase ( enum.Enum ): lowerCamelCase : int = 0 lowerCamelCase : Tuple = 1 def lowercase_ ( _lowercase , _lowercase="" ) -> str: '''simple docstring''' sys.stdout.write(str(__UpperCamelCase ) + end ) sys.stdout.flush() def lowercase_ ( _lowercase , _lowercase , _lowercase="" ) -> Optional[int]: '''simple docstring''' forceWrite(F"""\u001b[{color}m{content}\u001b[0m""" , __UpperCamelCase ) def lowercase_ ( ) -> List[str]: '''simple docstring''' forceWrite('''\r''' ) def lowercase_ ( _lowercase , _lowercase ) -> Any: '''simple docstring''' forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def lowercase_ ( ) -> Any: '''simple docstring''' forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def lowercase_ ( ) -> Union[str, Any]: '''simple docstring''' reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
318
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowercase : def __init__( self ,A__ ,): lowercase = parent lowercase = 1_3 lowercase = 7 lowercase = 3_0 lowercase = self.seq_length + self.mem_len lowercase = 1_5 lowercase = True lowercase = True lowercase = 9_9 lowercase = [1_0, 5_0, 8_0] lowercase = 3_2 lowercase = 3_2 lowercase = 4 lowercase = 8 lowercase = 1_2_8 lowercase = 2 lowercase = 2 lowercase = None lowercase = 1 lowercase = 0 lowercase = 3 lowercase = self.vocab_size - 1 lowercase = 0.01 def A__ ( self): lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) lowercase = None if self.use_labels: lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) lowercase = TransfoXLConfig( vocab_size=self.vocab_size ,mem_len=self.mem_len ,clamp_len=self.clamp_len ,cutoffs=self.cutoffs ,d_model=self.hidden_size ,d_embed=self.d_embed ,n_head=self.num_attention_heads ,d_head=self.d_head ,d_inner=self.d_inner ,div_val=self.div_val ,n_layer=self.num_hidden_layers ,eos_token_id=self.eos_token_id ,pad_token_id=self.vocab_size - 1 ,init_range=self.init_range ,num_labels=self.num_labels ,) return (config, input_ids_a, input_ids_a, lm_labels) def A__ ( self): random.seed(self.seed) tf.random.set_seed(self.seed) def A__ ( self ,A__ ,A__ ,A__ ,A__): lowercase = TFTransfoXLModel(_lowerCamelCase) lowercase , lowercase = model(_lowerCamelCase).to_tuple() lowercase = {'''input_ids''': input_ids_a, '''mems''': mems_a} lowercase , lowercase = model(_lowerCamelCase).to_tuple() self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def A__ ( self ,A__ ,A__ ,A__ ,A__): lowercase = TFTransfoXLLMHeadModel(_lowerCamelCase) lowercase , lowercase = model(_lowerCamelCase).to_tuple() lowercase = {'''input_ids''': input_ids_a, '''labels''': lm_labels} lowercase , lowercase = model(_lowerCamelCase).to_tuple() lowercase , lowercase = model([input_ids_a, mems_a]).to_tuple() lowercase = {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels} lowercase , lowercase = model(_lowerCamelCase).to_tuple() self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def A__ ( self ,A__ ,A__ ,A__ ,A__): lowercase = TFTransfoXLForSequenceClassification(_lowerCamelCase) lowercase = model(_lowerCamelCase) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels)) def A__ ( self): lowercase = self.prepare_config_and_inputs() ((lowercase) , (lowercase) , (lowercase) , (lowercase)) = config_and_inputs lowercase = {'''input_ids''': input_ids_a} return config, inputs_dict @require_tf class lowercase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): lowercase_ : str =( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) lowercase_ : Optional[int] =() if is_tf_available() else () lowercase_ : Optional[Any] =( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented lowercase_ : int =False lowercase_ : Optional[int] =False lowercase_ : Dict =False lowercase_ : str =False def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def A__ ( self): lowercase = TFTransfoXLModelTester(self) lowercase = ConfigTester(self ,config_class=_lowerCamelCase ,d_embed=3_7) def A__ ( self): self.config_tester.run_common_tests() def A__ ( self): self.model_tester.set_seed() lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*_lowerCamelCase) def A__ ( self): self.model_tester.set_seed() lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*_lowerCamelCase) def A__ ( self): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_lowerCamelCase) def A__ ( self): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: lowercase = model_class(_lowerCamelCase) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer) if model_class in list_other_models_with_output_ebd: lowercase = model.get_output_embeddings() assert isinstance(_lowerCamelCase ,tf.keras.layers.Layer) lowercase = model.get_bias() assert name is None else: lowercase = model.get_output_embeddings() assert x is None lowercase = model.get_bias() assert name is None def A__ ( self): pass @slow def A__ ( self): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase = TFTransfoXLModel.from_pretrained(_lowerCamelCase) self.assertIsNotNone(_lowerCamelCase) @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.''') def A__ ( self): pass @require_tf class lowercase ( unittest.TestCase ): @unittest.skip('''Skip test until #12651 is resolved.''') @slow def A__ ( self): lowercase = TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103''') # fmt: off lowercase = tf.convert_to_tensor([[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0]] ,dtype=tf.intaa) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off lowercase = [3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0,3_3,1,1_8_5_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_8,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> lowercase = model.generate(_lowerCamelCase ,max_length=2_0_0 ,do_sample=_lowerCamelCase) self.assertListEqual(output_ids[0].numpy().tolist() ,_lowerCamelCase)
101
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE_ : Any = logging.getLogger(__name__) @dataclass class a ( _lowerCAmelCase ): """simple docstring""" UpperCAmelCase = field( default=0.0, metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) UpperCAmelCase = field(default=_lowerCAmelCase, metadata={"help": "Whether to SortishSamler or not."} ) UpperCAmelCase = field( default=_lowerCAmelCase, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) UpperCAmelCase = field(default=_lowerCAmelCase, metadata={"help": "whether to use adafactor"} ) UpperCAmelCase = field( default=_lowerCAmelCase, metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) UpperCAmelCase = field( default=_lowerCAmelCase, metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) UpperCAmelCase = field(default=_lowerCAmelCase, metadata={"help": "Dropout probability. Goes into model.config."} ) UpperCAmelCase = field( default=_lowerCAmelCase, metadata={"help": "Attention dropout probability. Goes into model.config."} ) UpperCAmelCase = field( default="linear", metadata={"help": F'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'}, )
335
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": lowercase : List[Any] = argparse.ArgumentParser( description=( "Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="roberta", choices=["roberta", "gpt2"]) parser.add_argument("--model_name", default="roberta-large", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_roberta_048131723.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") lowercase : Any = parser.parse_args() if args.model_type == "roberta": lowercase : Optional[int] = RobertaForMaskedLM.from_pretrained(args.model_name) lowercase : List[Any] = "roberta" elif args.model_type == "gpt2": lowercase : Dict = GPTaLMHeadModel.from_pretrained(args.model_name) lowercase : Any = "transformer" lowercase : str = model.state_dict() lowercase : Dict = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: lowercase : str = state_dict[F'''{prefix}.{param_name}'''] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: lowercase : List[str] = F'''{prefix}.embeddings.{w}.weight''' lowercase : Union[str, Any] = state_dict[param_name] for w in ["weight", "bias"]: lowercase : Union[str, Any] = F'''{prefix}.embeddings.LayerNorm.{w}''' lowercase : List[str] = state_dict[param_name] # Transformer Blocks # lowercase : Union[str, Any] = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: lowercase : Union[str, Any] = state_dict[ F'''{prefix}.h.{teacher_idx}.{layer}.{w}''' ] lowercase : str = state_dict[F'''{prefix}.h.{teacher_idx}.attn.bias'''] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: lowercase : Union[str, Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}''' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: lowercase : Dict = state_dict[F'''{layer}'''] if args.vocab_transform: for w in ["weight", "bias"]: lowercase : List[Any] = state_dict[F'''lm_head.dense.{w}'''] lowercase : Dict = state_dict[F'''lm_head.layer_norm.{w}'''] elif args.model_type == "gpt2": for w in ["weight", "bias"]: lowercase : Optional[Any] = state_dict[F'''{prefix}.ln_f.{w}'''] lowercase : Optional[int] = state_dict["lm_head.weight"] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
42
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""simple docstring""" from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING a : List[str] = logging.get_logger(__name__) @add_end_docstrings(_lowerCAmelCase ) class __UpperCamelCase ( _lowerCAmelCase ): def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> Union[str, Any]: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) requires_backends(self , "decord" ) self.check_model_type(_lowerCamelCase ) def __a ( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None ) -> Tuple: a : int = {} if frame_sampling_rate is not None: a : Dict = frame_sampling_rate if num_frames is not None: a : Optional[int] = num_frames a : List[Any] = {} if top_k is not None: a : Dict = top_k return preprocess_params, {}, postprocess_params def __call__( self , lowerCAmelCase__ , **lowerCAmelCase__ ) -> Optional[Any]: return super().__call__(_lowerCamelCase , **_lowerCamelCase ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=1 ) -> Tuple: if num_frames is None: a : int = self.model.config.num_frames if video.startswith("http://" ) or video.startswith("https://" ): a : List[Any] = BytesIO(requests.get(_lowerCamelCase ).content ) a : List[Any] = VideoReader(_lowerCamelCase ) videoreader.seek(0 ) a : Dict = 0 a : Optional[int] = num_frames * frame_sampling_rate - 1 a : Optional[int] = np.linspace(_lowerCamelCase , _lowerCamelCase , num=_lowerCamelCase , dtype=np.intaa ) a : Dict = videoreader.get_batch(_lowerCamelCase ).asnumpy() a : Tuple = list(_lowerCamelCase ) a : List[Any] = self.image_processor(_lowerCamelCase , return_tensors=self.framework ) return model_inputs def __a ( self , lowerCAmelCase__ ) -> List[Any]: a : Optional[int] = self.model(**_lowerCamelCase ) return model_outputs def __a ( self , lowerCAmelCase__ , lowerCAmelCase__=5 ) -> Any: if top_k > self.model.config.num_labels: a : Dict = self.model.config.num_labels if self.framework == "pt": a : Optional[Any] = model_outputs.logits.softmax(-1 )[0] a, a : Dict = probs.topk(_lowerCamelCase ) else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) a : int = scores.tolist() a : List[str] = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCamelCase , _lowerCamelCase )]
105
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else mask_token super().__init__( errors=_lowerCamelCase, bos_token=_lowerCamelCase, eos_token=_lowerCamelCase, unk_token=_lowerCamelCase, sep_token=_lowerCamelCase, cls_token=_lowerCamelCase, pad_token=_lowerCamelCase, mask_token=_lowerCamelCase, add_prefix_space=_lowerCamelCase, **_lowerCamelCase, ) with open(_lowerCamelCase, encoding='''utf-8''' ) as vocab_handle: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = j if word[i] == first and i < len(_lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase ).split(''' ''' ) ) return bpe_tokens def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=_lowerCamelCase, ensure_ascii=_lowerCamelCase ) + '''\n''' ) __A = 0 with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda _lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase, token_ids_a=_lowerCamelCase, already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1] def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = kwargs.pop('''add_prefix_space''', self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase ) > 0 and not text[0].isspace()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : Dict = '▁' lowerCamelCase : List[str] = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} lowerCamelCase : Union[str, Any] = { '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', }, } lowerCamelCase : int = {'vinai/bartpho-syllable': 1_024} class __lowerCAmelCase (_lowerCAmelCase ): '''simple docstring''' lowerCAmelCase__ : str = VOCAB_FILES_NAMES lowerCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : Tuple = ["input_ids", "attention_mask"] def __init__(self : List[str] , UpperCamelCase : Union[str, Any] , UpperCamelCase : List[Any] , UpperCamelCase : List[str]="<s>" , UpperCamelCase : Union[str, Any]="</s>" , UpperCamelCase : Any="</s>" , UpperCamelCase : Dict="<s>" , UpperCamelCase : Dict="<unk>" , UpperCamelCase : List[Any]="<pad>" , UpperCamelCase : Tuple="<mask>" , UpperCamelCase : Optional[Dict[str, Any]] = None , **UpperCamelCase : List[Any] , ): '''simple docstring''' lowercase__ = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token lowercase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) lowercase__ = vocab_file lowercase__ = monolingual_vocab_file lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCamelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility lowercase__ = {} lowercase__ = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_lowerCamelCase ) not in self.fairseq_tokens_to_ids: lowercase__ = cnt cnt += 1 with open(_lowerCamelCase , '''r''' , encoding='''utf-8''' ) as f: for line in f.readlines(): lowercase__ = line.strip().split()[0] lowercase__ = len(self.fairseq_tokens_to_ids ) if str(_lowerCamelCase ) not in self.fairseq_tokens_to_ids: lowercase__ = len(self.fairseq_tokens_to_ids ) lowercase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__(self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.__dict__.copy() lowercase__ = None lowercase__ = self.sp_model.serialized_model_proto() return state def __setstate__(self : Union[str, Any] , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase__ = {} lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase__ = [self.cls_token_id] lowercase__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None , UpperCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1] def UpperCamelCase__ (self : Dict , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase__ (self : Any , UpperCamelCase : str ): '''simple docstring''' return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def UpperCamelCase__ (self : Dict , UpperCamelCase : Optional[int] ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase , ''' ''' ).strip() return out_string def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase__ = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file'''] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: lowercase__ = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _lowerCamelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_lowerCamelCase , '''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(_lowerCamelCase )} \n" ) return out_vocab_file, out_monolingual_vocab_file
2
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
"""simple docstring""" from __future__ import annotations import math def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = u for i in range(1 ,__UpperCamelCase ): SCREAMING_SNAKE_CASE__ : Any = temp * (u - i) return temp def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(input("""enter the numbers of values: """ ) ) SCREAMING_SNAKE_CASE__ : List[str] = [] for _ in range(__UpperCamelCase ): y.append([] ) for i in range(__UpperCamelCase ): for j in range(__UpperCamelCase ): y[i].append(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Tuple = 0 print("""enter the values of parameters in a list: """ ) SCREAMING_SNAKE_CASE__ : Dict = list(map(__UpperCamelCase ,input().split() ) ) print("""enter the values of corresponding parameters: """ ) for i in range(__UpperCamelCase ): SCREAMING_SNAKE_CASE__ : List[str] = float(input() ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("""enter the value to interpolate: """ ) ) SCREAMING_SNAKE_CASE__ : Dict = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 ,__UpperCamelCase ): for j in range(n - i ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = y[j + 1][i - 1] - y[j][i - 1] SCREAMING_SNAKE_CASE__ : Optional[Any] = y[0][0] for i in range(1 ,__UpperCamelCase ): summ += (ucal(__UpperCamelCase ,__UpperCamelCase ) * y[0][i]) / math.factorial(__UpperCamelCase ) print(f'''the value at {value} is {summ}''' ) if __name__ == "__main__": main()
25
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class __A( _lowerCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RoFormerTokenizer SCREAMING_SNAKE_CASE__ = RoFormerTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): super().setUp() def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer_class.from_pretrained("""junnyu/roformer_chinese_base""" , **_lowerCamelCase ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return self.rust_tokenizer_class.from_pretrained("""junnyu/roformer_chinese_base""" , **_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = """永和服装饰品有限公司,今天天气非常好""" UpperCamelCase__ = """永和 服装 饰品 有限公司 , 今 天 天 气 非常 好""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ , UpperCamelCase__ = self.get_chinese_input_output_texts() UpperCamelCase__ = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , output_text.split() ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , _lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ , UpperCamelCase__ = self.get_chinese_input_output_texts() UpperCamelCase__ = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , output_text.split() ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , _lowerCamelCase ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): pass
244
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase, model_name='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
'''simple docstring''' def __lowerCamelCase ( A__ = 1_000 ) -> int: """simple docstring""" return sum(e for e in range(3 , __UpperCamelCase ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f'''{solution() = }''')
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
"""simple docstring""" from __future__ import annotations from collections.abc import MutableSequence class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ,lowercase_ : int ,lowercase_ : MutableSequence[float] ): if len(_lowerCamelCase ) != degree + 1: raise ValueError( '''The number of coefficients should be equal to the degree + 1.''' ) lowerCAmelCase__ : Optional[int] = list(_lowerCamelCase ) lowerCAmelCase__ : str = degree def __add__( self : List[Any] ,lowercase_ : Polynomial ): if self.degree > polynomial_a.degree: lowerCAmelCase__ : str = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree ,_lowerCamelCase ) else: lowerCAmelCase__ : Any = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree ,_lowerCamelCase ) def __sub__( self : Optional[int] ,lowercase_ : Polynomial ): return self + polynomial_a * Polynomial(0 ,[-1] ) def __neg__( self : Optional[int] ): return Polynomial(self.degree ,[-c for c in self.coefficients] ) def __mul__( self : List[Any] ,lowercase_ : Polynomial ): lowerCAmelCase__ : str = [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 ,_lowerCamelCase ) def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : int | float ): lowerCAmelCase__ : int = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Tuple ): lowerCAmelCase__ : str = '''''' 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(_lowerCamelCase ) return polynomial def __repr__( self : List[str] ): return self.__str__() def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : Dict = [0] * self.degree for i in range(self.degree ): lowerCAmelCase__ : int = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 ,_lowerCamelCase ) def __lowerCAmelCase ( self : List[str] ,lowercase_ : int | float = 0 ): lowerCAmelCase__ : Union[str, Any] = [0] * (self.degree + 2) lowerCAmelCase__ : Tuple = constant for i in range(self.degree + 1 ): lowerCAmelCase__ : int = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 ,_lowerCamelCase ) def __eq__( self : Optional[int] ,lowercase_ : object ): if not isinstance(_lowerCamelCase ,_lowerCamelCase ): 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 : List[Any] ,lowercase_ : object ): return not self.__eq__(_lowerCamelCase )
106
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": a_ = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') a_ = F"""https://www.google.com/search?q={query}&num=100""" a_ = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: a_ = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: a_ = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __lowercase ( _lowerCAmelCase ): lowerCamelCase : int = "char" lowerCamelCase : str = "bpe" lowerCamelCase : List[str] = "wp" __lowercase : Tuple = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __lowercase ( _lowerCAmelCase ): lowerCamelCase : Any = ["image_processor", "char_tokenizer"] lowerCamelCase : Union[str, Any] = "ViTImageProcessor" lowerCamelCase : int = "MgpstrTokenizer" def __init__(self , A=None , A=None , **A ): lowerCamelCase_ : Any = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _lowerCamelCase , ) lowerCamelCase_ : int = kwargs.pop('''feature_extractor''' ) lowerCamelCase_ : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) lowerCamelCase_ : Union[str, Any] = tokenizer lowerCamelCase_ : int = AutoTokenizer.from_pretrained('''gpt2''' ) lowerCamelCase_ : Any = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(_lowerCamelCase , _lowerCamelCase ) def __call__(self , A=None , A=None , A=None , **A ): if images is None and text is None: raise ValueError('''You need to specify either an `images` or `text` input to process.''' ) if images is not None: lowerCamelCase_ : str = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is not None: lowerCamelCase_ : List[Any] = self.char_tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is None: return inputs elif images is None: return encodings else: lowerCamelCase_ : List[Any] = encodings['''input_ids'''] return inputs def UpperCAmelCase__ (self , A ): lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ : Tuple = sequences lowerCamelCase_ : List[Any] = char_preds.size(0 ) lowerCamelCase_, lowerCamelCase_ : List[str] = self._decode_helper(_lowerCamelCase , '''char''' ) lowerCamelCase_, lowerCamelCase_ : Tuple = self._decode_helper(_lowerCamelCase , '''bpe''' ) lowerCamelCase_, lowerCamelCase_ : List[Any] = self._decode_helper(_lowerCamelCase , '''wp''' ) lowerCamelCase_ : Tuple = [] lowerCamelCase_ : str = [] for i in range(_lowerCamelCase ): lowerCamelCase_ : str = [char_scores[i], bpe_scores[i], wp_scores[i]] lowerCamelCase_ : Any = [char_strs[i], bpe_strs[i], wp_strs[i]] lowerCamelCase_ : Dict = scores.index(max(_lowerCamelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) lowerCamelCase_ : str = {} lowerCamelCase_ : Any = final_strs lowerCamelCase_ : Tuple = final_scores lowerCamelCase_ : int = char_strs lowerCamelCase_ : Union[str, Any] = bpe_strs lowerCamelCase_ : Union[str, Any] = wp_strs return out def UpperCAmelCase__ (self , A , A ): if format == DecodeType.CHARACTER: lowerCamelCase_ : Optional[int] = self.char_decode lowerCamelCase_ : List[str] = 1 lowerCamelCase_ : Any = '''[s]''' elif format == DecodeType.BPE: lowerCamelCase_ : Any = self.bpe_decode lowerCamelCase_ : Tuple = 2 lowerCamelCase_ : List[Any] = '''#''' elif format == DecodeType.WORDPIECE: lowerCamelCase_ : List[Any] = self.wp_decode lowerCamelCase_ : int = 1_0_2 lowerCamelCase_ : Union[str, Any] = '''[SEP]''' else: raise ValueError(F"""Format {format} is not supported.""" ) lowerCamelCase_, lowerCamelCase_ : Union[str, Any] = [], [] lowerCamelCase_ : str = pred_logits.size(0 ) lowerCamelCase_ : Dict = pred_logits.size(1 ) lowerCamelCase_, lowerCamelCase_ : Optional[int] = pred_logits.topk(1 , dim=-1 , largest=_lowerCamelCase , sorted=_lowerCamelCase ) lowerCamelCase_ : int = preds_index.view(-1 , _lowerCamelCase )[:, 1:] lowerCamelCase_ : Tuple = decoder(_lowerCamelCase ) lowerCamelCase_, lowerCamelCase_ : Dict = torch.nn.functional.softmax(_lowerCamelCase , dim=2 ).max(dim=2 ) lowerCamelCase_ : Optional[Any] = preds_max_prob[:, 1:] for index in range(_lowerCamelCase ): lowerCamelCase_ : str = preds_str[index].find(_lowerCamelCase ) lowerCamelCase_ : Tuple = preds_str[index][:pred_eos] lowerCamelCase_ : Optional[int] = preds_index[index].cpu().tolist() lowerCamelCase_ : List[str] = pred_index.index(_lowerCamelCase ) if eos_token in pred_index else -1 lowerCamelCase_ : Tuple = preds_max_prob[index][: pred_eos_index + 1] lowerCamelCase_ : List[str] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(_lowerCamelCase ) conf_scores.append(_lowerCamelCase ) return dec_strs, conf_scores def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Any = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(_lowerCamelCase )] return decode_strs def UpperCAmelCase__ (self , A ): return self.bpe_tokenizer.batch_decode(_lowerCamelCase ) def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Optional[Any] = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(_lowerCamelCase )] return decode_strs
318
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase__ :Optional[int] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) lowercase__ :List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCamelCase ( ): '''simple docstring''' lowercase = '''https://pypi.org/pypi/diffusers/json''' lowercase = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda lowerCAmelCase__ : version.Version(__UpperCamelCase ) ) def UpperCamelCase ( ): '''simple docstring''' if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) lowercase = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' init_hf_modules() lowercase = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) lowercase = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: lowercase = f.read() # Imports of the form `import .xxx` lowercase = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = False lowercase = [module_file] lowercase = [] # Let's recurse through all relative imports while not no_change: lowercase = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) lowercase = Path(__UpperCamelCase ).parent lowercase = [str(module_path / m ) for m in new_imports] lowercase = [f for f in new_import_files if f not in all_relative_imports] lowercase = [f'{f}.py' for f in new_import_files] lowercase = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: lowercase = f.read() # Imports of the form `import xxx` lowercase = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module lowercase = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase = list(set(__UpperCamelCase ) ) lowercase = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = module_path.replace(os.path.sep , '''.''' ) lowercase = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' from ..pipelines import DiffusionPipeline lowercase = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) lowercase = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) lowercase = cls return pipeline_class def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , ): '''simple docstring''' lowercase = str(__UpperCamelCase ) lowercase = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): lowercase = module_file_or_url lowercase = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase = get_diffusers_versions() # cut ".dev0" lowercase = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: lowercase = f'v{revision}' elif revision == "main": lowercase = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub lowercase = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: lowercase = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) lowercase = '''git''' lowercase = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached lowercase = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) lowercase = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment lowercase = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. lowercase = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) lowercase = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: lowercase = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): lowercase = use_auth_token elif use_auth_token is True: lowercase = HfFolder.get_token() else: lowercase = None lowercase = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase = submodule_path / commit_hash lowercase = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , **lowerCAmelCase__ , ): '''simple docstring''' lowercase = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" from __future__ import annotations class a : """simple docstring""" def __init__( self: int , UpperCamelCase: List[Any]=None ): """simple docstring""" A__ = data A__ = None def __repr__( self: Union[str, Any] ): """simple docstring""" A__ = [] A__ = self while temp: string_rep.append(f"""{temp.data}""" ) A__ = temp.next return "->".join(_lowerCamelCase ) def _snake_case ( UpperCAmelCase_ : Dict ): if not elements_list: raise Exception("""The Elements List is empty""" ) A__ = A__ = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): A__ = Node(elements_list[i] ) A__ = current.next return head def _snake_case ( UpperCAmelCase_ : List[Any] ): if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def _snake_case ( ): from doctest import testmod testmod() A__ = make_linked_list([14, 52, 14, 12, 43] ) print("""Linked List:""" ) print(__UpperCamelCase ) print("""Elements in Reverse:""" ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
335
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''apply_ocr''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'''height''': 42, '''width''': 42} ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) self.assertIsInstance(encoding.words, _lowerCamelCase ) self.assertIsInstance(encoding.boxes, _lowerCamelCase ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput lowercase : Optional[int] = 8 def SCREAMING_SNAKE_CASE__ ( __A , __A=BITS ) -> Any: _snake_case = x.device _snake_case = (x * 255).int().clamp(0 , 255 ) _snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__UpperCamelCase ) _snake_case = rearrange(__UpperCamelCase , 'd -> d 1 1' ) _snake_case = rearrange(__UpperCamelCase , 'b c h w -> b c 1 h w' ) _snake_case = ((x & mask) != 0).float() _snake_case = rearrange(__UpperCamelCase , 'b c d h w -> b (c d) h w' ) _snake_case = bits * 2 - 1 return bits def SCREAMING_SNAKE_CASE__ ( __A , __A=BITS ) -> Dict: _snake_case = x.device _snake_case = (x > 0).int() _snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__UpperCamelCase , dtype=torch.intaa ) _snake_case = rearrange(__UpperCamelCase , 'd -> d 1 1' ) _snake_case = rearrange(__UpperCamelCase , 'b (c d) h w -> b c d h w' , d=8 ) _snake_case = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def SCREAMING_SNAKE_CASE__ ( self , __A , __A , __A , __A = 0.0 , __A = True , __A=None , __A = True , ) -> Optional[Any]: if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) _snake_case = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _snake_case = self.alphas_cumprod[timestep] _snake_case = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _snake_case = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _snake_case = self.bit_scale if self.config.clip_sample: _snake_case = torch.clamp(__UpperCamelCase , -scale , __UpperCamelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _snake_case = self._get_variance(__UpperCamelCase , __UpperCamelCase ) _snake_case = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _snake_case = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 _snake_case = model_output.device if torch.is_tensor(__UpperCamelCase ) else 'cpu' _snake_case = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__UpperCamelCase ).to(__UpperCamelCase ) _snake_case = self._get_variance(__UpperCamelCase , __UpperCamelCase ) ** 0.5 * eta * noise _snake_case = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__UpperCamelCase , pred_original_sample=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , __A , __A , __A , __A="epsilon" , __A=None , __A = True , ) -> Dict: _snake_case = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _snake_case , _snake_case = torch.split(__UpperCamelCase , sample.shape[1] , dim=1 ) else: _snake_case = None # 1. compute alphas, betas _snake_case = self.alphas_cumprod[t] _snake_case = self.alphas_cumprod[t - 1] if t > 0 else self.one _snake_case = 1 - alpha_prod_t _snake_case = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": _snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _snake_case = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" _snake_case = self.bit_scale if self.config.clip_sample: _snake_case = torch.clamp(__UpperCamelCase , -scale , __UpperCamelCase ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _snake_case = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _snake_case = 0 if t > 0: _snake_case = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__UpperCamelCase ).to(model_output.device ) _snake_case = (self._get_variance(__UpperCamelCase , predicted_variance=__UpperCamelCase ) ** 0.5) * noise _snake_case = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__UpperCamelCase , pred_original_sample=__UpperCamelCase ) class __UpperCAmelCase ( _lowerCAmelCase ): def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 1.0 , ): """simple docstring""" super().__init__() _snake_case = bit_scale _snake_case = ( ddim_bit_scheduler_step if isinstance(_lowerCamelCase , _lowerCamelCase ) else ddpm_bit_scheduler_step ) self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) @torch.no_grad() def __call__( self , lowerCAmelCase_ = 2_56 , lowerCAmelCase_ = 2_56 , lowerCAmelCase_ = 50 , lowerCAmelCase_ = None , lowerCAmelCase_ = 1 , lowerCAmelCase_ = "pil" , lowerCAmelCase_ = True , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=_lowerCamelCase , ) _snake_case = decimal_to_bits(_lowerCamelCase ) * self.bit_scale _snake_case = latents.to(self.device ) self.scheduler.set_timesteps(_lowerCamelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual _snake_case = self.unet(_lowerCamelCase , _lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 _snake_case = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample _snake_case = bits_to_decimal(_lowerCamelCase ) if output_type == "pil": _snake_case = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowerCamelCase )
42
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def _SCREAMING_SNAKE_CASE ( _lowercase : Optional[Any] , _lowercase : Union[str, Any] , _lowercase : str ) ->Any: '''simple docstring''' a : Tuple = OmegaConf.load(__UpperCamelCase ) a : Union[str, Any] = torch.load(__UpperCamelCase , map_location="cpu" )["model"] a : Union[str, Any] = list(state_dict.keys() ) # extract state_dict for VQVAE a : Optional[int] = {} a : Optional[Any] = "first_stage_model." for key in keys: if key.startswith(__UpperCamelCase ): a : Tuple = state_dict[key] # extract state_dict for UNetLDM a : Dict = {} a : int = "model.diffusion_model." for key in keys: if key.startswith(__UpperCamelCase ): a : Optional[int] = state_dict[key] a : Union[str, Any] = config.model.params.first_stage_config.params a : str = config.model.params.unet_config.params a : Any = VQModel(**__UpperCamelCase ).eval() vqvae.load_state_dict(__UpperCamelCase ) a : Tuple = UNetLDMModel(**__UpperCamelCase ).eval() unet.load_state_dict(__UpperCamelCase ) a : Optional[int] = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule="scaled_linear" , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=__UpperCamelCase , ) a : Any = LDMPipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) pipeline.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": a : int = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', type=str, required=True) parser.add_argument('''--config_path''', type=str, required=True) parser.add_argument('''--output_path''', type=str, required=True) a : Union[str, Any] = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
105
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCamelCase : Optional[Any] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : List[str] = PegasusConfig lowerCAmelCase__ : Dict = {} lowerCAmelCase__ : Union[str, Any] = "gelu" def __init__(self : int , UpperCamelCase : Any , UpperCamelCase : str=13 , UpperCamelCase : Tuple=7 , UpperCamelCase : int=True , UpperCamelCase : Any=False , UpperCamelCase : str=99 , UpperCamelCase : int=32 , UpperCamelCase : Union[str, Any]=5 , UpperCamelCase : str=4 , UpperCamelCase : str=37 , UpperCamelCase : Optional[int]=0.1 , UpperCamelCase : Dict=0.1 , UpperCamelCase : Optional[int]=20 , UpperCamelCase : Any=2 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=0 , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = eos_token_id lowercase__ = pad_token_id lowercase__ = bos_token_id def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) lowercase__ = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) lowercase__ = np.concatenate([input_ids, eos_tensor] , axis=1 ) lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowercase__ = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = 20 lowercase__ = model_class_name(_lowerCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] ) lowercase__ ,lowercase__ = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase__ = model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) lowercase__ = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowercase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ = model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) lowercase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_lowerCamelCase , ) lowercase__ = model.decode(_lowerCamelCase , _lowerCamelCase ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = 20 lowercase__ = model_class_name(_lowerCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] ) lowercase__ ,lowercase__ = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase__ = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowercase__ = model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) lowercase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ = model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) lowercase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) lowercase__ = model.decode(_lowerCamelCase , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _SCREAMING_SNAKE_CASE (A , A , A , A=None , A=None , ) -> int: """simple docstring""" if attention_mask is None: lowercase__ = np.not_equal(__UpperCamelCase , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: lowercase__ = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __lowerCAmelCase (_lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[Any] = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) lowerCAmelCase__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () lowerCAmelCase__ : Any = True lowerCAmelCase__ : Union[str, Any] = False lowerCAmelCase__ : Dict = False lowerCAmelCase__ : List[Any] = False def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = FlaxPegasusModelTester(self ) lowercase__ = ConfigTester(self , config_class=_lowerCamelCase ) def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) lowercase__ = model_class(_lowerCamelCase ) @jax.jit def encode_jitted(UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int]=None , **UpperCamelCase : Dict ): return model.encode(input_ids=_lowerCamelCase , attention_mask=_lowerCamelCase ) with self.subTest('''JIT Enabled''' ): lowercase__ = encode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase__ = encode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ = model_class(_lowerCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) lowercase__ = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(UpperCamelCase : int , UpperCamelCase : List[str] , UpperCamelCase : Optional[Any] ): return model.decode( decoder_input_ids=_lowerCamelCase , decoder_attention_mask=_lowerCamelCase , encoder_outputs=_lowerCamelCase , ) with self.subTest('''JIT Enabled''' ): lowercase__ = decode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase__ = decode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase__ (self : List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: lowercase__ = model_class_name.from_pretrained('''google/pegasus-large''' , from_pt=_lowerCamelCase ) lowercase__ = np.ones((1, 1) ) lowercase__ = model(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @slow def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = FlaxPegasusForConditionalGeneration.from_pretrained('''google/pegasus-xsum''' ) lowercase__ = PegasusTokenizer.from_pretrained('''google/pegasus-xsum''' ) lowercase__ = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] lowercase__ = [ '''California\'s largest electricity provider has turned off power to hundreds of thousands of customers.''', '''Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.''', ] lowercase__ = tokenizer(_lowerCamelCase , return_tensors='''np''' , truncation=_lowerCamelCase , max_length=512 , padding=_lowerCamelCase ) lowercase__ = model.generate(**_lowerCamelCase , num_beams=2 ).sequences lowercase__ = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) assert tgt_text == decoded
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" UpperCAmelCase__ : Tuple = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1_000} SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__UpperCamelCase ): if (place + 1 < len(__UpperCamelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : int = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Union[str, Any] = divmod(__UpperCamelCase ,__UpperCamelCase ) result.append(roman * factor ) if number == 0: break return "".join(__UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
25
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
def __magic_name__ ( __a : Any ): '''simple docstring''' UpperCamelCase__ = [0] * len(__UpperCamelCase ) for i in range(1 , len(__UpperCamelCase ) ): # use last results for better performance - dynamic programming UpperCamelCase__ = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: UpperCamelCase__ = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 UpperCamelCase__ = j return prefix_result def __magic_name__ ( __a : Tuple ): '''simple docstring''' return max(prefix_function(__UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod()
244
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): """simple docstring""" def A ( self : Any ): """simple docstring""" UpperCamelCase = SMALL_MODEL_IDENTIFIER UpperCamelCase = 'pt' UpperCamelCase = 'tf' def A ( self : Optional[int] , UpperCamelCase__ : int ): """simple docstring""" UpperCamelCase = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(_lowerCamelCase ) def A ( self : Dict , UpperCamelCase__ : Optional[Any] ): """simple docstring""" UpperCamelCase = TFAutoModel.from_pretrained(self.test_model , from_pt=_lowerCamelCase ) model_tf.save_pretrained(_lowerCamelCase ) def A ( self : Tuple ): """simple docstring""" UpperCamelCase = 'mock_framework' # Framework provided - return whatever the user provides UpperCamelCase = FeaturesManager.determine_framework(self.test_model , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_lowerCamelCase ) UpperCamelCase = FeaturesManager.determine_framework(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_lowerCamelCase ) UpperCamelCase = FeaturesManager.determine_framework(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def A ( self : Tuple ): """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_lowerCamelCase ) UpperCamelCase = FeaturesManager.determine_framework(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_lowerCamelCase ) UpperCamelCase = FeaturesManager.determine_framework(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(_lowerCamelCase ): UpperCamelCase = FeaturesManager.determine_framework(_lowerCamelCase ) def A ( self : str ): """simple docstring""" UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) with patch('transformers.onnx.features.is_tf_available' , _lowerCamelCase ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowerCamelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) with patch('transformers.onnx.features.is_torch_available' , _lowerCamelCase ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowerCamelCase , self.framework_tf ) # Both in environment -> use PyTorch UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) with patch('transformers.onnx.features.is_tf_available' , _lowerCamelCase ), patch( 'transformers.onnx.features.is_torch_available' , _lowerCamelCase ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowerCamelCase , self.framework_pt ) # Both not in environment -> raise error UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) UpperCamelCase = MagicMock(return_value=_lowerCamelCase ) with patch('transformers.onnx.features.is_tf_available' , _lowerCamelCase ), patch( 'transformers.onnx.features.is_torch_available' , _lowerCamelCase ): with self.assertRaises(_lowerCamelCase ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model )
28
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): """simple docstring""" lowercase__ = "ctrl" lowercase__ = ["past_key_values"] lowercase__ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Union[str, Any] ,lowercase_ : List[str]=2_4_6_5_3_4 ,lowercase_ : Dict=2_5_6 ,lowercase_ : Dict=1_2_8_0 ,lowercase_ : int=8_1_9_2 ,lowercase_ : Optional[int]=4_8 ,lowercase_ : Tuple=1_6 ,lowercase_ : Tuple=0.1 ,lowercase_ : Optional[Any]=0.1 ,lowercase_ : Dict=1E-6 ,lowercase_ : List[Any]=0.02 ,lowercase_ : Tuple=True ,**lowercase_ : Union[str, Any] ,): lowerCAmelCase__ : Optional[int] = vocab_size lowerCAmelCase__ : List[Any] = n_positions lowerCAmelCase__ : Tuple = n_embd lowerCAmelCase__ : int = n_layer lowerCAmelCase__ : Any = n_head lowerCAmelCase__ : Union[str, Any] = dff lowerCAmelCase__ : int = resid_pdrop lowerCAmelCase__ : Optional[int] = embd_pdrop lowerCAmelCase__ : Union[str, Any] = layer_norm_epsilon lowerCAmelCase__ : str = initializer_range lowerCAmelCase__ : List[Any] = use_cache super().__init__(**_lowerCamelCase )
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
from __future__ import annotations a_ = tuple[int, int, int] a_ = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase a_ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selection -------------------------- # rotors -------------------------- a_ = 'EGZWVONAHDCLFQMSIPJBYUKXTR' a_ = 'FOBHMDKEXQNRAULPGSJVTYICZW' a_ = 'ZJXESIUQLHAVRMDOYGTNFWPBKC' # reflector -------------------------- a_ = { '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 -------------------------- a_ = 'RMDJXFUWGISLHVTCQNKYPBEZOA' a_ = 'SGLCPQWZHKXAREONTFBVIYJUDM' a_ = 'HVSICLTYKQUBXDWAJZOMFGPREN' a_ = 'RZWQHFMVDBKICJLNTUXAGYPSOE' a_ = 'LFKIJODBEGAMQPXVUHYSTCZRWN' a_ = 'KOAEGVDHXPQZMLFTYWJNBRCIUS' def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : Tuple , lowerCamelCase : Tuple ): if (unique_rotsel := len(set(__UpperCamelCase ) )) < 3: UpperCamelCase_ : int = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(__UpperCamelCase ) # Checks if rotor positions are valid UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Dict = rotpos if not 0 < rotorposa <= len(__UpperCamelCase ): UpperCamelCase_ : Dict = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(__UpperCamelCase ) if not 0 < rotorposa <= len(__UpperCamelCase ): UpperCamelCase_ : Optional[int] = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(__UpperCamelCase ) if not 0 < rotorposa <= len(__UpperCamelCase ): UpperCamelCase_ : Optional[Any] = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(__UpperCamelCase ) # Validates string and returns dict UpperCamelCase_ : Optional[int] = _plugboard(__UpperCamelCase ) return rotpos, rotsel, pbdict def __lowercase ( lowerCamelCase : Any ): if not isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase_ : int = F"Plugboard setting isn\'t type string ({type(__UpperCamelCase )})" raise TypeError(__UpperCamelCase ) elif len(__UpperCamelCase ) % 2 != 0: UpperCamelCase_ : Tuple = F"Odd number of symbols ({len(__UpperCamelCase )})" raise Exception(__UpperCamelCase ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique UpperCamelCase_ : Optional[int] = set() for i in pbstring: if i not in abc: UpperCamelCase_ : List[str] = F"\'{i}\' not in list of symbols" raise Exception(__UpperCamelCase ) elif i in tmppbl: UpperCamelCase_ : Dict = F"Duplicate symbol ({i})" raise Exception(__UpperCamelCase ) else: tmppbl.add(__UpperCamelCase ) del tmppbl # Created the dictionary UpperCamelCase_ : Optional[Any] = {} for j in range(0 , len(__UpperCamelCase ) - 1 , 2 ): UpperCamelCase_ : List[str] = pbstring[j + 1] UpperCamelCase_ : List[str] = pbstring[j] return pb def __lowercase ( lowerCamelCase : Any , lowerCamelCase : Tuple , lowerCamelCase : str = (rotora, rotora, rotora) , lowerCamelCase : Optional[int] = "" , ): UpperCamelCase_ : Any = text.upper() UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Dict = _validator( __UpperCamelCase , __UpperCamelCase , plugb.upper() ) UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Optional[int] = rotor_position UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Tuple = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 UpperCamelCase_ : Union[str, Any] = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: UpperCamelCase_ : List[str] = plugboard[symbol] # rotor ra -------------------------- UpperCamelCase_ : List[Any] = abc.index(__UpperCamelCase ) + rotorposa UpperCamelCase_ : str = rotora[index % len(__UpperCamelCase )] # rotor rb -------------------------- UpperCamelCase_ : Any = abc.index(__UpperCamelCase ) + rotorposa UpperCamelCase_ : Union[str, Any] = rotora[index % len(__UpperCamelCase )] # rotor rc -------------------------- UpperCamelCase_ : Optional[int] = abc.index(__UpperCamelCase ) + rotorposa UpperCamelCase_ : str = rotora[index % len(__UpperCamelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher UpperCamelCase_ : Any = reflector[symbol] # 2nd rotors UpperCamelCase_ : str = abc[rotora.index(__UpperCamelCase ) - rotorposa] UpperCamelCase_ : Dict = abc[rotora.index(__UpperCamelCase ) - rotorposa] UpperCamelCase_ : Optional[int] = abc[rotora.index(__UpperCamelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: UpperCamelCase_ : List[Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(__UpperCamelCase ): UpperCamelCase_ : Dict = 0 rotorposa += 1 if rotorposa >= len(__UpperCamelCase ): UpperCamelCase_ : List[Any] = 0 rotorposa += 1 if rotorposa >= len(__UpperCamelCase ): UpperCamelCase_ : Union[str, Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(__UpperCamelCase ) return "".join(__UpperCamelCase ) if __name__ == "__main__": a_ = 'This is my Python script that emulates the Enigma machine from WWII.' a_ = (1, 1, 1) a_ = 'pictures' a_ = (rotora, rotora, rotora) a_ = enigma(message, rotor_pos, rotor_sel, pb) print('Encrypted message:', en) print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
175
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) __A = 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 : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __lowercase ( _lowerCAmelCase ): lowerCamelCase : torch.FloatTensor class __lowercase ( nn.Module ): def __init__(self , A=3 , A=3 , A=("DownEncoderBlock2D",) , A=(6_4,) , A=2 , A=3_2 , A="silu" , A=True , ): super().__init__() lowerCamelCase_ : Any = layers_per_block lowerCamelCase_ : Optional[Any] = torch.nn.Convad( _lowerCamelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) lowerCamelCase_ : Union[str, Any] = None lowerCamelCase_ : Dict = nn.ModuleList([] ) # down lowerCamelCase_ : List[Any] = block_out_channels[0] for i, down_block_type in enumerate(_lowerCamelCase ): lowerCamelCase_ : List[Any] = output_channel lowerCamelCase_ : Dict = block_out_channels[i] lowerCamelCase_ : Union[str, Any] = i == len(_lowerCamelCase ) - 1 lowerCamelCase_ : Union[str, Any] = get_down_block( _lowerCamelCase , num_layers=self.layers_per_block , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=_lowerCamelCase , resnet_groups=_lowerCamelCase , attention_head_dim=_lowerCamelCase , temb_channels=_lowerCamelCase , ) self.down_blocks.append(_lowerCamelCase ) # mid lowerCamelCase_ : List[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=_lowerCamelCase , output_scale_factor=1 , resnet_time_scale_shift='''default''' , attention_head_dim=block_out_channels[-1] , resnet_groups=_lowerCamelCase , temb_channels=_lowerCamelCase , ) # out lowerCamelCase_ : Optional[Any] = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=_lowerCamelCase , eps=1E-6 ) lowerCamelCase_ : str = nn.SiLU() lowerCamelCase_ : Optional[int] = 2 * out_channels if double_z else out_channels lowerCamelCase_ : Tuple = nn.Convad(block_out_channels[-1] , _lowerCamelCase , 3 , padding=1 ) lowerCamelCase_ : Optional[int] = False def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Optional[Any] = x lowerCamelCase_ : Optional[int] = self.conv_in(_lowerCamelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(A ): def custom_forward(*A ): return module(*_lowerCamelCase ) return custom_forward # down if is_torch_version('''>=''' , '''1.11.0''' ): for down_block in self.down_blocks: lowerCamelCase_ : Union[str, Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , use_reentrant=_lowerCamelCase ) # middle lowerCamelCase_ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , use_reentrant=_lowerCamelCase ) else: for down_block in self.down_blocks: lowerCamelCase_ : List[Any] = torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCamelCase ) , _lowerCamelCase ) # middle lowerCamelCase_ : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , _lowerCamelCase ) else: # down for down_block in self.down_blocks: lowerCamelCase_ : int = down_block(_lowerCamelCase ) # middle lowerCamelCase_ : Tuple = self.mid_block(_lowerCamelCase ) # post-process lowerCamelCase_ : Optional[Any] = self.conv_norm_out(_lowerCamelCase ) lowerCamelCase_ : Union[str, Any] = self.conv_act(_lowerCamelCase ) lowerCamelCase_ : Tuple = self.conv_out(_lowerCamelCase ) return sample class __lowercase ( nn.Module ): def __init__(self , A=3 , A=3 , A=("UpDecoderBlock2D",) , A=(6_4,) , A=2 , A=3_2 , A="silu" , A="group" , ): super().__init__() lowerCamelCase_ : Tuple = layers_per_block lowerCamelCase_ : Optional[int] = nn.Convad( _lowerCamelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) lowerCamelCase_ : int = None lowerCamelCase_ : List[Any] = nn.ModuleList([] ) lowerCamelCase_ : Tuple = in_channels if norm_type == '''spatial''' else None # mid lowerCamelCase_ : Union[str, Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=_lowerCamelCase , output_scale_factor=1 , resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=_lowerCamelCase , temb_channels=_lowerCamelCase , ) # up lowerCamelCase_ : Union[str, Any] = list(reversed(_lowerCamelCase ) ) lowerCamelCase_ : Dict = reversed_block_out_channels[0] for i, up_block_type in enumerate(_lowerCamelCase ): lowerCamelCase_ : Tuple = output_channel lowerCamelCase_ : str = reversed_block_out_channels[i] lowerCamelCase_ : Optional[int] = i == len(_lowerCamelCase ) - 1 lowerCamelCase_ : Any = get_up_block( _lowerCamelCase , num_layers=self.layers_per_block + 1 , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , prev_output_channel=_lowerCamelCase , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=_lowerCamelCase , resnet_groups=_lowerCamelCase , attention_head_dim=_lowerCamelCase , temb_channels=_lowerCamelCase , resnet_time_scale_shift=_lowerCamelCase , ) self.up_blocks.append(_lowerCamelCase ) lowerCamelCase_ : Any = output_channel # out if norm_type == "spatial": lowerCamelCase_ : Dict = SpatialNorm(block_out_channels[0] , _lowerCamelCase ) else: lowerCamelCase_ : Dict = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=_lowerCamelCase , eps=1E-6 ) lowerCamelCase_ : List[Any] = nn.SiLU() lowerCamelCase_ : str = nn.Convad(block_out_channels[0] , _lowerCamelCase , 3 , padding=1 ) lowerCamelCase_ : Optional[Any] = False def UpperCAmelCase__ (self , A , A=None ): lowerCamelCase_ : Optional[int] = z lowerCamelCase_ : Dict = self.conv_in(_lowerCamelCase ) lowerCamelCase_ : Any = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A ): def custom_forward(*A ): return module(*_lowerCamelCase ) return custom_forward if is_torch_version('''>=''' , '''1.11.0''' ): # middle lowerCamelCase_ : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , _lowerCamelCase , use_reentrant=_lowerCamelCase ) lowerCamelCase_ : Any = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: lowerCamelCase_ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , use_reentrant=_lowerCamelCase ) else: # middle lowerCamelCase_ : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , _lowerCamelCase ) lowerCamelCase_ : Optional[Any] = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: lowerCamelCase_ : Optional[Any] = torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase ) else: # middle lowerCamelCase_ : List[str] = self.mid_block(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase_ : List[Any] = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: lowerCamelCase_ : Tuple = up_block(_lowerCamelCase , _lowerCamelCase ) # post-process if latent_embeds is None: lowerCamelCase_ : str = self.conv_norm_out(_lowerCamelCase ) else: lowerCamelCase_ : Dict = self.conv_norm_out(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase_ : str = self.conv_act(_lowerCamelCase ) lowerCamelCase_ : List[str] = self.conv_out(_lowerCamelCase ) return sample class __lowercase ( nn.Module ): def __init__(self , A , A , A , A=None , A="random" , A=False , A=True ): super().__init__() lowerCamelCase_ : List[str] = n_e lowerCamelCase_ : Union[str, Any] = vq_embed_dim lowerCamelCase_ : Dict = beta lowerCamelCase_ : str = legacy lowerCamelCase_ : List[str] = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) lowerCamelCase_ : Tuple = remap if self.remap is not None: self.register_buffer('''used''' , torch.tensor(np.load(self.remap ) ) ) lowerCamelCase_ : str = self.used.shape[0] lowerCamelCase_ : Dict = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": lowerCamelCase_ : Union[str, Any] = self.re_embed lowerCamelCase_ : Union[str, Any] = self.re_embed + 1 print( F"""Remapping {self.n_e} indices to {self.re_embed} indices. """ F"""Using {self.unknown_index} for unknown indices.""" ) else: lowerCamelCase_ : int = n_e lowerCamelCase_ : List[str] = sane_index_shape def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Optional[Any] = inds.shape assert len(_lowerCamelCase ) > 1 lowerCamelCase_ : Optional[int] = inds.reshape(ishape[0] , -1 ) lowerCamelCase_ : Any = self.used.to(_lowerCamelCase ) lowerCamelCase_ : Optional[int] = (inds[:, :, None] == used[None, None, ...]).long() lowerCamelCase_ : Dict = match.argmax(-1 ) lowerCamelCase_ : int = match.sum(2 ) < 1 if self.unknown_index == "random": lowerCamelCase_ : Union[str, Any] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: lowerCamelCase_ : Union[str, Any] = self.unknown_index return new.reshape(_lowerCamelCase ) def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Optional[int] = inds.shape assert len(_lowerCamelCase ) > 1 lowerCamelCase_ : Tuple = inds.reshape(ishape[0] , -1 ) lowerCamelCase_ : str = self.used.to(_lowerCamelCase ) if self.re_embed > self.used.shape[0]: # extra token lowerCamelCase_ : Tuple = 0 # simply set to zero lowerCamelCase_ : Dict = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , _lowerCamelCase ) return back.reshape(_lowerCamelCase ) def UpperCAmelCase__ (self , A ): lowerCamelCase_ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() lowerCamelCase_ : Optional[int] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z lowerCamelCase_ : List[str] = torch.argmin(torch.cdist(_lowerCamelCase , self.embedding.weight ) , dim=1 ) lowerCamelCase_ : Optional[int] = self.embedding(_lowerCamelCase ).view(z.shape ) lowerCamelCase_ : Union[str, Any] = None lowerCamelCase_ : List[str] = None # compute loss for embedding if not self.legacy: lowerCamelCase_ : List[str] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: lowerCamelCase_ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients lowerCamelCase_ : List[str] = z + (z_q - z).detach() # reshape back to match original input shape lowerCamelCase_ : int = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: lowerCamelCase_ : Optional[int] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis lowerCamelCase_ : Dict = self.remap_to_used(_lowerCamelCase ) lowerCamelCase_ : Tuple = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: lowerCamelCase_ : List[Any] = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def UpperCAmelCase__ (self , A , A ): # shape specifying (batch, height, width, channel) if self.remap is not None: lowerCamelCase_ : Optional[int] = indices.reshape(shape[0] , -1 ) # add batch axis lowerCamelCase_ : Any = self.unmap_to_all(_lowerCamelCase ) lowerCamelCase_ : str = indices.reshape(-1 ) # flatten again # get quantized latent vectors lowerCamelCase_ : Dict = self.embedding(_lowerCamelCase ) if shape is not None: lowerCamelCase_ : int = z_q.view(_lowerCamelCase ) # reshape back to match original input shape lowerCamelCase_ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __lowercase ( _lowerCAmelCase ): def __init__(self , A , A=False ): lowerCamelCase_ : Dict = parameters lowerCamelCase_, lowerCamelCase_ : List[Any] = torch.chunk(_lowerCamelCase , 2 , dim=1 ) lowerCamelCase_ : Optional[int] = torch.clamp(self.logvar , -30.0 , 20.0 ) lowerCamelCase_ : Optional[Any] = deterministic lowerCamelCase_ : int = torch.exp(0.5 * self.logvar ) lowerCamelCase_ : int = torch.exp(self.logvar ) if self.deterministic: lowerCamelCase_ : Tuple = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def UpperCAmelCase__ (self , A = None ): lowerCamelCase_ : List[str] = randn_tensor( self.mean.shape , generator=_lowerCamelCase , device=self.parameters.device , dtype=self.parameters.dtype ) lowerCamelCase_ : Tuple = self.mean + self.std * sample return x def UpperCAmelCase__ (self , A=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def UpperCAmelCase__ (self , A , A=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) lowerCamelCase_ : Union[str, Any] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=_lowerCamelCase ) def UpperCAmelCase__ (self ): return self.mean
318
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = [False] * len(__UpperCamelCase ) lowercase = [-1] * len(__UpperCamelCase ) def dfs(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = True lowercase = c for u in graph[v]: if not visited[u]: dfs(__UpperCamelCase , 1 - c ) for i in range(len(__UpperCamelCase ) ): if not visited[i]: dfs(__UpperCamelCase , 0 ) for i in range(len(__UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph lowercase__ :Any = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
101
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def _snake_case ( UpperCAmelCase_ : str ): if isinstance(__UpperCamelCase , torch.Tensor ): return image elif isinstance(__UpperCamelCase , PIL.Image.Image ): A__ = [image] A__ = [trans(img.convert("""RGB""" ) ) for img in image] A__ = torch.stack(__UpperCamelCase ) return image class a ( _lowerCAmelCase ): """simple docstring""" def __init__( self: Tuple , UpperCamelCase: Dict , UpperCamelCase: Union[str, Any] ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM A__ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) def UpperCamelCase ( self: Tuple , UpperCamelCase: Dict ): """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f"""The value of strength should in [0.0, 1.0] but is {strength}""" ) def UpperCamelCase ( self: Dict , UpperCamelCase: Any , UpperCamelCase: Dict , UpperCamelCase: Optional[Any] ): """simple docstring""" A__ = min(int(num_inference_steps * strength ) , _lowerCamelCase ) A__ = max(num_inference_steps - init_timestep , 0 ) A__ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCamelCase ( self: Dict , UpperCamelCase: Dict , UpperCamelCase: Union[str, Any] , UpperCamelCase: Dict , UpperCamelCase: str , UpperCamelCase: str , UpperCamelCase: List[str]=None ): """simple docstring""" if not isinstance(_lowerCamelCase , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_lowerCamelCase )}""" ) A__ = image.to(device=_lowerCamelCase , dtype=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(_lowerCamelCase )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) A__ = init_latents.shape A__ = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase , device=_lowerCamelCase , dtype=_lowerCamelCase ) # get latents print("""add noise to latents at timestep""" , _lowerCamelCase ) A__ = self.scheduler.add_noise(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) A__ = init_latents return latents @torch.no_grad() def __call__( self: Dict , UpperCamelCase: Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCamelCase: float = 0.8 , UpperCamelCase: int = 1 , UpperCamelCase: Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase: float = 0.0 , UpperCamelCase: int = 50 , UpperCamelCase: Optional[bool] = None , UpperCamelCase: Optional[str] = "pil" , UpperCamelCase: bool = True , ): """simple docstring""" self.check_inputs(_lowerCamelCase ) # 2. Preprocess image A__ = preprocess(_lowerCamelCase ) # 3. set timesteps self.scheduler.set_timesteps(_lowerCamelCase , device=self.device ) A__ , A__ = self.get_timesteps(_lowerCamelCase , _lowerCamelCase , self.device ) A__ = timesteps[:1].repeat(_lowerCamelCase ) # 4. Prepare latent variables A__ = self.prepare_latents(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , self.unet.dtype , self.device , _lowerCamelCase ) A__ = latents # 5. Denoising loop for t in self.progress_bar(_lowerCamelCase ): # 1. predict noise model_output A__ = self.unet(_lowerCamelCase , _lowerCamelCase ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A__ = self.scheduler.step( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , eta=_lowerCamelCase , use_clipped_model_output=_lowerCamelCase , generator=_lowerCamelCase , ).prev_sample A__ = (image / 2 + 0.5).clamp(0 , 1 ) A__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A__ = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_lowerCamelCase )
335
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A="attention" ) -> List[Any]: _snake_case = params[F'{prefix}/layers_{i}/{layer_name}/key/kernel'] _snake_case = params[F'{prefix}/layers_{i}/{layer_name}/out/kernel'] _snake_case = params[F'{prefix}/layers_{i}/{layer_name}/query/kernel'] _snake_case = params[F'{prefix}/layers_{i}/{layer_name}/value/kernel'] return k, o, q, v def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A=False ) -> Dict: if split_mlp_wi: _snake_case = params[F'{prefix}/layers_{i}/mlp/wi_0/kernel'] _snake_case = params[F'{prefix}/layers_{i}/mlp/wi_1/kernel'] _snake_case = (wi_a, wi_a) else: _snake_case = params[F'{prefix}/layers_{i}/mlp/wi/kernel'] _snake_case = params[F'{prefix}/layers_{i}/mlp/wo/kernel'] return wi, wo def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A ) -> List[Any]: return params[F'{prefix}/layers_{i}/{layer_name}/scale'] def SCREAMING_SNAKE_CASE__ ( __A , *, __A , __A ) -> Dict: _snake_case = traverse_util.flatten_dict(variables['target'] ) _snake_case = {'/'.join(__UpperCamelCase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _snake_case = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , __UpperCamelCase ) _snake_case = collections.OrderedDict() # Shared embeddings. _snake_case = old['token_embedder/embedding'] # Encoder. for i in range(__UpperCamelCase ): # Block i, layer 0 (Self Attention). _snake_case = tax_layer_norm_lookup(__UpperCamelCase , __UpperCamelCase , 'encoder' , 'pre_attention_layer_norm' ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(__UpperCamelCase , __UpperCamelCase , 'encoder' , 'attention' ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 1 (MLP). _snake_case = tax_layer_norm_lookup(__UpperCamelCase , __UpperCamelCase , 'encoder' , 'pre_mlp_layer_norm' ) _snake_case , _snake_case = tax_mlp_lookup(__UpperCamelCase , __UpperCamelCase , 'encoder' , __UpperCamelCase ) _snake_case = layer_norm if split_mlp_wi: _snake_case = wi[0].T _snake_case = wi[1].T else: _snake_case = wi.T _snake_case = wo.T _snake_case = old[ 'encoder/relpos_bias/rel_embedding' ].T _snake_case = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(__UpperCamelCase ): # Block i, layer 0 (Self Attention). _snake_case = tax_layer_norm_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , 'pre_self_attention_layer_norm' ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , 'self_attention' ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 1 (Cross Attention). _snake_case = tax_layer_norm_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , 'pre_cross_attention_layer_norm' ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , 'encoder_decoder_attention' ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 2 (MLP). _snake_case = tax_layer_norm_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , 'pre_mlp_layer_norm' ) _snake_case , _snake_case = tax_mlp_lookup(__UpperCamelCase , __UpperCamelCase , 'decoder' , __UpperCamelCase ) _snake_case = layer_norm if split_mlp_wi: _snake_case = wi[0].T _snake_case = wi[1].T else: _snake_case = wi.T _snake_case = wo.T _snake_case = old['decoder/decoder_norm/scale'] _snake_case = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _snake_case = old['decoder/logits_dense/kernel'].T return new def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[Any]: _snake_case = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _snake_case = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _snake_case = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) _snake_case = state_dict['shared.weight'] return state_dict def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A ) -> Union[str, Any]: _snake_case = checkpoints.load_tax_checkpoint(__UpperCamelCase ) _snake_case = convert_tax_to_pytorch(__UpperCamelCase , num_layers=config.num_layers , is_encoder_only=__UpperCamelCase ) _snake_case = make_state_dict(__UpperCamelCase , __UpperCamelCase ) model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A = False ) -> Tuple: _snake_case = TaConfig.from_json_file(__UpperCamelCase ) print(F'Building PyTorch model from configuration: {config}' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _snake_case = TaEncoderModel(__UpperCamelCase ) else: _snake_case = TaForConditionalGeneration(__UpperCamelCase ) # Load weights from tf checkpoint load_tax_weights_in_ta(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__UpperCamelCase ) # Verify that we can load the checkpoint. model.from_pretrained(__UpperCamelCase ) print('Done' ) if __name__ == "__main__": lowercase : List[str] = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) lowercase : List[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
42
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""simple docstring""" import requests from bsa import BeautifulSoup def _SCREAMING_SNAKE_CASE ( _lowercase : Any , _lowercase : Union[str, Any] ) ->Any: '''simple docstring''' a : Union[str, Any] = BeautifulSoup(requests.get(__UpperCamelCase , params=__UpperCamelCase ).content , "html.parser" ) a : Dict = soup.find("div" , attrs={"class": "gs_ri"} ) a : List[str] = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": a : Tuple = { '''title''': ( '''Precisely geometry controlled microsupercapacitors for ultrahigh areal ''' '''capacitance, volumetric capacitance, and energy density''' ), '''journal''': '''Chem. Mater.''', '''volume''': 30, '''pages''': '''3979-3990''', '''year''': 2018, '''hl''': '''en''', } print(get_citation('''https://scholar.google.com/scholar_lookup''', params=params))
105
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else mask_token super().__init__( errors=_lowerCamelCase, bos_token=_lowerCamelCase, eos_token=_lowerCamelCase, unk_token=_lowerCamelCase, sep_token=_lowerCamelCase, cls_token=_lowerCamelCase, pad_token=_lowerCamelCase, mask_token=_lowerCamelCase, add_prefix_space=_lowerCamelCase, **_lowerCamelCase, ) with open(_lowerCamelCase, encoding='''utf-8''' ) as vocab_handle: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = j if word[i] == first and i < len(_lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase ).split(''' ''' ) ) return bpe_tokens def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=_lowerCamelCase, ensure_ascii=_lowerCamelCase ) + '''\n''' ) __A = 0 with open(_lowerCamelCase, '''w''', encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda _lowerCamelCase : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase, token_ids_a=_lowerCamelCase, already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1] def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = kwargs.pop('''add_prefix_space''', self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase ) > 0 and not text[0].isspace()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCamelCase : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Dict = '▁' UpperCAmelCase__ : Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': { 'facebook/mbart-large-50-one-to-many-mmt': ( 'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model' ), } } UpperCAmelCase__ : int = { 'facebook/mbart-large-50-one-to-many-mmt': 1_0_2_4, } # fmt: off UpperCAmelCase__ : Any = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI'] class lowerCAmelCase_ (_lowerCAmelCase ): """simple docstring""" __UpperCamelCase : Tuple = VOCAB_FILES_NAMES __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = ["input_ids", "attention_mask"] __UpperCamelCase : List[int] = [] __UpperCamelCase : List[int] = [] def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="<mask>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__ : Dict = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ : int = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : int = len(self.sp_model ) SCREAMING_SNAKE_CASE__ : str = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowerCamelCase ) } SCREAMING_SNAKE_CASE__ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE__ : Optional[int] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE__ : Any = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE__ : int = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE__ : List[str] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __magic_name__ (self ) -> str: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __magic_name__ (self ) -> List[Any]: """simple docstring""" return self._src_lang @src_lang.setter def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__(self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : str = None return state def __setstate__(self , SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ : int = self.sp_model.PieceToId(_lowerCamelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Tuple = """""" SCREAMING_SNAKE_CASE__ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : List[str] = [] else: current_sub_tokens.append(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> int: """simple docstring""" if not os.path.isdir(_lowerCamelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join( _lowerCamelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Tuple = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : List[str] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_lowerCamelCase )) + suffix_ones return prefix_ones + ([0] * len(_lowerCamelCase )) + ([0] * len(_lowerCamelCase )) + suffix_ones def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> Any: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Any = src_lang SCREAMING_SNAKE_CASE__ : str = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : int = tgt_lang_id return inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "en_XX" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "ro_RO" , **SCREAMING_SNAKE_CASE__ , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = src_lang SCREAMING_SNAKE_CASE__ : Optional[int] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __magic_name__ (self ) -> Dict: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id] def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.lang_code_to_id[tgt_lang] SCREAMING_SNAKE_CASE__ : List[Any] = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE__ : str = [self.eos_token_id]
25
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
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 __A( unittest.TestCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=4 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_attention_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_choices def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_attention_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = 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 UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A( _lowerCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase_ (self ): UpperCamelCase__ = FlaxRoFormerModelTester(self ) @slow def UpperCAmelCase_ (self ): for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_lowerCamelCase ) UpperCamelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) UpperCamelCase__ = jnp.array([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(_lowerCamelCase )[0] UpperCamelCase__ = 5_00_00 UpperCamelCase__ = (1, 6, vocab_size) self.assertEqual(output.shape , _lowerCamelCase ) UpperCamelCase__ = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1E-4 ) )
244
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase, model_name='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __lowerCamelCase ( A__ ) -> Tuple: """simple docstring""" UpperCamelCase = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: UpperCamelCase = 4 UpperCamelCase = 48 UpperCamelCase = 'pixelshuffle_aux' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase = [6, 6, 6, 6] UpperCamelCase = 60 UpperCamelCase = [6, 6, 6, 6] UpperCamelCase = 'pixelshuffledirect' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase = 4 UpperCamelCase = 'nearest+conv' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: UpperCamelCase = 1 UpperCamelCase = 1 UpperCamelCase = 126 UpperCamelCase = 7 UpperCamelCase = 255.0 UpperCamelCase = '' return config def __lowerCamelCase ( A__ , A__ ) -> Optional[Any]: """simple docstring""" if "patch_embed.proj" in name and "layers" not in name: UpperCamelCase = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase = name.replace('patch_embed.norm' , 'embeddings.patch_embeddings.layernorm' ) if "layers" in name: UpperCamelCase = name.replace('layers' , 'encoder.stages' ) if "residual_group.blocks" in name: UpperCamelCase = name.replace('residual_group.blocks' , 'layers' ) if "attn.proj" in name: UpperCamelCase = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: UpperCamelCase = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: UpperCamelCase = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: UpperCamelCase = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: UpperCamelCase = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if "patch_embed.proj" in name: UpperCamelCase = name.replace('patch_embed.proj' , 'patch_embed.projection' ) if name == "norm.weight": UpperCamelCase = 'layernorm.weight' if name == "norm.bias": UpperCamelCase = 'layernorm.bias' if "conv_first" in name: UpperCamelCase = name.replace('conv_first' , 'first_convolution' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: UpperCamelCase = name.replace('conv_last' , 'final_convolution' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: UpperCamelCase = name.replace('conv_before_upsample.0' , 'conv_before_upsample' ) if "upsample.0" in name: UpperCamelCase = name.replace('upsample.0' , 'upsample.convolution_0' ) if "upsample.2" in name: UpperCamelCase = name.replace('upsample.2' , 'upsample.convolution_1' ) UpperCamelCase = 'upsample.' + name elif config.upsampler == "pixelshuffledirect": UpperCamelCase = name.replace('upsample.0.weight' , 'upsample.conv.weight' ) UpperCamelCase = name.replace('upsample.0.bias' , 'upsample.conv.bias' ) else: pass else: UpperCamelCase = 'swin2sr.' + name return name def __lowerCamelCase ( A__ , A__ ) -> Dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase = orig_state_dict.pop(__UpperCamelCase ) if "qkv" in key: UpperCamelCase = key.split('.' ) UpperCamelCase = int(key_split[1] ) UpperCamelCase = int(key_split[4] ) UpperCamelCase = config.embed_dim if "weight" in key: UpperCamelCase = val[:dim, :] UpperCamelCase = val[dim : dim * 2, :] UpperCamelCase = val[-dim:, :] else: UpperCamelCase = val[:dim] UpperCamelCase = val[dim : dim * 2] UpperCamelCase = val[-dim:] pass else: UpperCamelCase = val return orig_state_dict def __lowerCamelCase ( A__ , A__ , A__ ) -> List[str]: """simple docstring""" UpperCamelCase = get_config(__UpperCamelCase ) UpperCamelCase = SwinaSRForImageSuperResolution(__UpperCamelCase ) model.eval() UpperCamelCase = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='cpu' ) UpperCamelCase = convert_state_dict(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase , UpperCamelCase = model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ValueError('Missing keys when converting: {}'.format(__UpperCamelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F"""Unexpected key {key} in state_dict""" ) # verify values UpperCamelCase = 'https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true' UpperCamelCase = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert('RGB' ) UpperCamelCase = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values UpperCamelCase = 126 if 'Jpeg' in checkpoint_url else 256 UpperCamelCase = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) UpperCamelCase = transforms(__UpperCamelCase ).unsqueeze(0 ) if config.num_channels == 1: UpperCamelCase = pixel_values[:, 0, :, :].unsqueeze(1 ) UpperCamelCase = model(__UpperCamelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 512, 512] ) UpperCamelCase = torch.tensor( [[-0.7_087, -0.7_138, -0.6_721], [-0.8_340, -0.8_095, -0.7_298], [-0.9_149, -0.8_414, -0.7_940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.7_775, -0.8_105, -0.8_933], [-0.7_764, -0.8_356, -0.9_225], [-0.7_976, -0.8_686, -0.9_579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.8_035, -0.7_504, -0.7_491], [-0.8_538, -0.8_124, -0.7_782], [-0.8_804, -0.8_651, -0.8_493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 512, 512] ) UpperCamelCase = torch.tensor( [[-0.7_669, -0.8_662, -0.8_767], [-0.8_810, -0.9_962, -0.9_820], [-0.9_340, -1.0_322, -1.1_149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.5_238, -0.5_557, -0.6_321], [-0.6_016, -0.5_903, -0.6_391], [-0.6_244, -0.6_334, -0.6_889]] ) assert ( outputs.reconstruction.shape == expected_shape ), F"""Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}""" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , __UpperCamelCase , atol=1e-3 ) print('Looks ok!' ) UpperCamelCase = { 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': ( 'swin2SR-classical-sr-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': ( 'swin2SR-classical-sr-x4-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': ( 'swin2SR-compressed-sr-x4-48' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': ( 'swin2SR-lightweight-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': ( 'swin2SR-realworld-sr-x4-64-bsrgan-psnr' ), } UpperCamelCase = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: model.push_to_hub(F"""caidas/{model_name}""" ) processor.push_to_hub(F"""caidas/{model_name}""" ) if __name__ == "__main__": _lowerCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth", type=str, help="URL of the original Swin2SR checkpoint you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the converted model to the hub.") _lowerCamelCase : int = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): """simple docstring""" lowercase__ = 42 lowercase__ = 42 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 .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('''>=''', '''0.0.12''') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): """simple docstring""" lowercase__ = 42 lowercase__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
106
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
from ..utils import DummyObject, requires_backends class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Optional[Any] , **snake_case : Tuple ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Optional[int] , *snake_case : Optional[Any] , **snake_case : Union[str, Any] ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : Any , **snake_case : int ) -> List[str]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Optional[int] , *snake_case : Any , **snake_case : Any ) -> Dict: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Tuple , *snake_case : List[Any] , **snake_case : Any ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : str , **snake_case : Tuple ) -> List[str]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Optional[int] , **snake_case : int ) -> Tuple: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Union[str, Any] , **snake_case : Optional[int] ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Optional[Any] , **snake_case : Tuple ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Any , *snake_case : Tuple , **snake_case : List[Any] ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : str , **snake_case : Dict ) -> int: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Optional[Any] , **snake_case : Optional[Any] ) -> List[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : str , *snake_case : Optional[int] , **snake_case : Dict ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : List[str] , **snake_case : int ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : Tuple , **snake_case : List[Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : List[str] , **snake_case : Optional[int] ) -> List[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Optional[int] , **snake_case : Any ) -> Optional[int]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Union[str, Any] , **snake_case : List[str] ) -> int: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[str] , *snake_case : Dict , **snake_case : Dict ) -> Tuple: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Optional[int] , *snake_case : Optional[int] , **snake_case : Optional[int] ) -> Tuple: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Optional[Any] , **snake_case : Any ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Optional[Any] , **snake_case : Optional[int] ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Union[str, Any] , **snake_case : Dict ) -> Optional[int]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : Optional[Any] , **snake_case : int ) -> Tuple: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : int ) -> Tuple: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : List[Any] , *snake_case : Optional[int] , **snake_case : Union[str, Any] ) -> List[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Dict , *snake_case : List[str] , **snake_case : List[Any] ) -> Dict: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Union[str, Any] , *snake_case : Optional[int] , **snake_case : List[str] ) -> Optional[int]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Tuple , *snake_case : Optional[Any] , **snake_case : Optional[int] ) -> Dict: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Any , *snake_case : Dict , **snake_case : List[Any] ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['sentencepiece'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : Dict , *snake_case : Any , **snake_case : Optional[int] ) -> Any: """simple docstring""" requires_backends(self , ['sentencepiece'] )
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowercase_ ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase=True , _lowercase="pt" ) -> Any: '''simple docstring''' lowerCamelCase_ : Optional[Any] = {'''add_prefix_space''': True} if isinstance(__UpperCamelCase , __UpperCamelCase ) and not line.startswith(''' ''' ) else {} lowerCamelCase_ : Union[str, Any] = padding_side return tokenizer( [line] , max_length=__UpperCamelCase , padding='''max_length''' if pad_to_max_length else None , truncation=__UpperCamelCase , return_tensors=__UpperCamelCase , add_special_tokens=__UpperCamelCase , **__UpperCamelCase , ) def lowercase_ ( _lowercase , _lowercase , _lowercase=None , ) -> Dict: '''simple docstring''' lowerCamelCase_ : str = input_ids.ne(__UpperCamelCase ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __lowercase ( _lowerCAmelCase ): def __init__(self , A , A , A , A , A="train" , A=None , A=None , A=None , A="" , ): super().__init__() lowerCamelCase_ : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) lowerCamelCase_ : List[str] = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) lowerCamelCase_ : int = self.get_char_lens(self.src_file ) lowerCamelCase_ : int = max_source_length lowerCamelCase_ : Any = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" lowerCamelCase_ : List[Any] = tokenizer lowerCamelCase_ : List[Any] = prefix if n_obs is not None: lowerCamelCase_ : Dict = self.src_lens[:n_obs] lowerCamelCase_ : Union[str, Any] = src_lang lowerCamelCase_ : Optional[Any] = tgt_lang def __len__(self ): return len(self.src_lens ) def __getitem__(self , A ): lowerCamelCase_ : Dict = index + 1 # linecache starts at 1 lowerCamelCase_ : List[str] = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) lowerCamelCase_ : int = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowerCamelCase_ : Union[str, Any] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) lowerCamelCase_ : List[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer lowerCamelCase_ : Optional[Any] = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) lowerCamelCase_ : Tuple = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) lowerCamelCase_ : List[Any] = source_inputs['''input_ids'''].squeeze() lowerCamelCase_ : Union[str, Any] = target_inputs['''input_ids'''].squeeze() lowerCamelCase_ : List[Any] = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def UpperCAmelCase__ (A ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def UpperCAmelCase__ (self , A ): lowerCamelCase_ : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) lowerCamelCase_ : Any = torch.stack([x['''attention_mask'''] for x in batch] ) lowerCamelCase_ : Dict = torch.stack([x['''decoder_input_ids'''] for x in batch] ) lowerCamelCase_ : Optional[Any] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCamelCase_ : Any = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCamelCase_ : str = trim_batch(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase_, lowerCamelCase_ : Optional[int] = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) lowerCamelCase_ : List[Any] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch __lowercase : str = getLogger(__name__) def lowercase_ ( _lowercase ) -> Optional[int]: '''simple docstring''' return list(itertools.chain.from_iterable(__UpperCamelCase ) ) def lowercase_ ( _lowercase ) -> str: '''simple docstring''' lowerCamelCase_ : Tuple = get_git_info() save_json(__UpperCamelCase , os.path.join(__UpperCamelCase , '''git_log.json''' ) ) def lowercase_ ( _lowercase , _lowercase , _lowercase=4 , **_lowercase ) -> Optional[int]: '''simple docstring''' with open(__UpperCamelCase , '''w''' ) as f: json.dump(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase , **__UpperCamelCase ) def lowercase_ ( _lowercase ) -> Any: '''simple docstring''' with open(__UpperCamelCase ) as f: return json.load(__UpperCamelCase ) def lowercase_ ( ) -> str: '''simple docstring''' lowerCamelCase_ : Any = git.Repo(search_parent_directories=__UpperCamelCase ) lowerCamelCase_ : Tuple = { '''repo_id''': str(__UpperCamelCase ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowercase_ ( _lowercase , _lowercase ) -> Optional[int]: '''simple docstring''' return list(map(__UpperCamelCase , __UpperCamelCase ) ) def lowercase_ ( _lowercase , _lowercase ) -> Optional[Any]: '''simple docstring''' with open(__UpperCamelCase , '''wb''' ) as f: return pickle.dump(__UpperCamelCase , __UpperCamelCase ) def lowercase_ ( _lowercase ) -> Any: '''simple docstring''' def remove_articles(_lowercase ): return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , __UpperCamelCase ) def white_space_fix(_lowercase ): return " ".join(text.split() ) def remove_punc(_lowercase ): lowerCamelCase_ : str = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowercase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__UpperCamelCase ) ) ) ) def lowercase_ ( _lowercase , _lowercase ) -> List[str]: '''simple docstring''' lowerCamelCase_ : Tuple = normalize_answer(__UpperCamelCase ).split() lowerCamelCase_ : str = normalize_answer(__UpperCamelCase ).split() lowerCamelCase_ : Dict = Counter(__UpperCamelCase ) & Counter(__UpperCamelCase ) lowerCamelCase_ : Any = sum(common.values() ) if num_same == 0: return 0 lowerCamelCase_ : Optional[Any] = 1.0 * num_same / len(__UpperCamelCase ) lowerCamelCase_ : Optional[int] = 1.0 * num_same / len(__UpperCamelCase ) lowerCamelCase_ : Any = (2 * precision * recall) / (precision + recall) return fa def lowercase_ ( _lowercase , _lowercase ) -> Optional[int]: '''simple docstring''' return normalize_answer(__UpperCamelCase ) == normalize_answer(__UpperCamelCase ) def lowercase_ ( _lowercase , _lowercase ) -> Dict: '''simple docstring''' assert len(__UpperCamelCase ) == len(__UpperCamelCase ) lowerCamelCase_ : Any = 0 for hypo, pred in zip(__UpperCamelCase , __UpperCamelCase ): em += exact_match_score(__UpperCamelCase , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: em /= len(__UpperCamelCase ) return {"em": em} def lowercase_ ( _lowercase ) -> Optional[Any]: '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowercase_ ( _lowercase , _lowercase , _lowercase ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ : List[str] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowerCamelCase_ : int = '''dropout_rate''' for p in extra_params: if getattr(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if not hasattr(__UpperCamelCase , __UpperCamelCase ) and not hasattr(__UpperCamelCase , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(__UpperCamelCase ) ) delattr(__UpperCamelCase , __UpperCamelCase ) continue lowerCamelCase_ : List[Any] = p if hasattr(__UpperCamelCase , __UpperCamelCase ) else equivalent_param[p] setattr(__UpperCamelCase , __UpperCamelCase , getattr(__UpperCamelCase , __UpperCamelCase ) ) delattr(__UpperCamelCase , __UpperCamelCase ) return hparams, config
318
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = torch.exp(__UpperCamelCase ) lowercase = torch.sum(__UpperCamelCase , dim=1 ) # sum of exp(x_i) lowercase = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(__UpperCamelCase ) - B / A class lowercase ( nn.Module ): def __init__( self ,A__): super().__init__() lowercase = config.output_attentions lowercase = config.output_hidden_states lowercase = nn.ModuleList([BertLayer(_lowerCamelCase) for _ in range(config.num_hidden_layers)]) lowercase = nn.ModuleList([BertHighway(_lowerCamelCase) for _ in range(config.num_hidden_layers)]) lowercase = [-1 for _ in range(config.num_hidden_layers)] def A__ ( self ,A__): if (type(_lowerCamelCase) is float) or (type(_lowerCamelCase) is int): for i in range(len(self.early_exit_entropy)): lowercase = x else: lowercase = x def A__ ( self ,A__): lowercase = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name]) def A__ ( self ,A__ ,A__=None ,A__=None ,A__=None ,A__=None ,): lowercase = () lowercase = () lowercase = () for i, layer_module in enumerate(self.layer): if self.output_hidden_states: lowercase = all_hidden_states + (hidden_states,) lowercase = layer_module( _lowerCamelCase ,_lowerCamelCase ,head_mask[i] ,_lowerCamelCase ,_lowerCamelCase) lowercase = layer_outputs[0] if self.output_attentions: lowercase = all_attentions + (layer_outputs[1],) lowercase = (hidden_states,) if self.output_hidden_states: lowercase = current_outputs + (all_hidden_states,) if self.output_attentions: lowercase = current_outputs + (all_attentions,) lowercase = self.highway[i](_lowerCamelCase) # logits, pooled_output if not self.training: lowercase = highway_exit[0] lowercase = entropy(_lowerCamelCase) lowercase = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy lowercase = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: lowercase = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(_lowerCamelCase ,i + 1) else: lowercase = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: lowercase = all_hidden_states + (hidden_states,) lowercase = (hidden_states,) if self.output_hidden_states: lowercase = outputs + (all_hidden_states,) if self.output_attentions: lowercase = outputs + (all_attentions,) lowercase = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( '''The Bert Model transformer with early exiting (DeeBERT). ''' , _lowerCAmelCase , ) class lowercase ( _lowerCAmelCase ): def __init__( self ,A__): super().__init__(_lowerCamelCase) lowercase = config lowercase = BertEmbeddings(_lowerCamelCase) lowercase = DeeBertEncoder(_lowerCamelCase) lowercase = BertPooler(_lowerCamelCase) self.init_weights() def A__ ( self): self.encoder.init_highway_pooler(self.pooler) def A__ ( self): return self.embeddings.word_embeddings def A__ ( self ,A__): lowercase = value def A__ ( self ,A__): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(_lowerCamelCase) @add_start_docstrings_to_model_forward(_lowerCamelCase) def A__ ( self ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,): if input_ids is not None and inputs_embeds is not None: raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''') elif input_ids is not None: lowercase = input_ids.size() elif inputs_embeds is not None: lowercase = inputs_embeds.size()[:-1] else: raise ValueError('''You have to specify either input_ids or inputs_embeds''') lowercase = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: lowercase = torch.ones(_lowerCamelCase ,device=_lowerCamelCase) if encoder_attention_mask is None: lowercase = torch.ones(_lowerCamelCase ,device=_lowerCamelCase) if token_type_ids is None: lowercase = torch.zeros(_lowerCamelCase ,dtype=torch.long ,device=_lowerCamelCase) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. lowercase = self.get_extended_attention_mask(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: lowercase = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: lowercase = encoder_attention_mask[:, None, None, :] lowercase = encoder_extended_attention_mask.to( dtype=next(self.parameters()).dtype) # fp16 compatibility lowercase = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] lowercase = self.get_head_mask(_lowerCamelCase ,self.config.num_hidden_layers) lowercase = self.embeddings( input_ids=_lowerCamelCase ,position_ids=_lowerCamelCase ,token_type_ids=_lowerCamelCase ,inputs_embeds=_lowerCamelCase) lowercase = self.encoder( _lowerCamelCase ,attention_mask=_lowerCamelCase ,head_mask=_lowerCamelCase ,encoder_hidden_states=_lowerCamelCase ,encoder_attention_mask=_lowerCamelCase ,) lowercase = encoder_outputs[0] lowercase = self.pooler(_lowerCamelCase) lowercase = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class lowercase ( _lowerCAmelCase ): def __init__( self ,A__ ,A__): lowercase = message lowercase = exit_layer # start from 1! class lowercase ( nn.Module ): def __init__( self ,A__): super().__init__() lowercase = BertPooler(_lowerCamelCase) lowercase = nn.Dropout(config.hidden_dropout_prob) lowercase = nn.Linear(config.hidden_size ,config.num_labels) def A__ ( self ,A__): lowercase = encoder_outputs[0] lowercase = self.pooler(_lowerCamelCase) # "return" pooler_output # BertModel lowercase = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification lowercase = bmodel_output[1] lowercase = self.dropout(_lowerCamelCase) lowercase = self.classifier(_lowerCamelCase) return logits, pooled_output @add_start_docstrings( '''Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ''' , _lowerCAmelCase , ) class lowercase ( _lowerCAmelCase ): def __init__( self ,A__): super().__init__(_lowerCamelCase) lowercase = config.num_labels lowercase = config.num_hidden_layers lowercase = DeeBertModel(_lowerCamelCase) lowercase = nn.Dropout(config.hidden_dropout_prob) lowercase = nn.Linear(config.hidden_size ,self.config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(_lowerCamelCase) def A__ ( self ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=None ,A__=-1 ,A__=False ,): lowercase = self.num_layers try: lowercase = self.bert( _lowerCamelCase ,attention_mask=_lowerCamelCase ,token_type_ids=_lowerCamelCase ,position_ids=_lowerCamelCase ,head_mask=_lowerCamelCase ,inputs_embeds=_lowerCamelCase ,) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits lowercase = outputs[1] lowercase = self.dropout(_lowerCamelCase) lowercase = self.classifier(_lowerCamelCase) lowercase = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: lowercase = e.message lowercase = e.exit_layer lowercase = outputs[0] if not self.training: lowercase = entropy(_lowerCamelCase) lowercase = [] lowercase = [] if labels is not None: if self.num_labels == 1: # We are doing regression lowercase = MSELoss() lowercase = loss_fct(logits.view(-1) ,labels.view(-1)) else: lowercase = CrossEntropyLoss() lowercase = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) # work with highway exits lowercase = [] for highway_exit in outputs[-1]: lowercase = highway_exit[0] if not self.training: highway_logits_all.append(_lowerCamelCase) highway_entropy.append(highway_exit[2]) if self.num_labels == 1: # We are doing regression lowercase = MSELoss() lowercase = loss_fct(highway_logits.view(-1) ,labels.view(-1)) else: lowercase = CrossEntropyLoss() lowercase = loss_fct(highway_logits.view(-1 ,self.num_labels) ,labels.view(-1)) highway_losses.append(_lowerCamelCase) if train_highway: lowercase = (sum(highway_losses[:-1]),) + outputs # exclude the final highway, of course else: lowercase = (loss,) + outputs if not self.training: lowercase = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: lowercase = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : Optional[int] ): if not numbers: return 0 if not isinstance(__UpperCamelCase , (list, tuple) ) or not all( isinstance(__UpperCamelCase , __UpperCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) A__ = A__ = A__ = numbers[0] for i in range(1 , len(__UpperCamelCase ) ): # update the maximum and minimum subarray products A__ = numbers[i] if number < 0: A__ , A__ = min_till_now, max_till_now A__ = max(__UpperCamelCase , max_till_now * number ) A__ = min(__UpperCamelCase , min_till_now * number ) # update the maximum product found till now A__ = max(__UpperCamelCase , __UpperCamelCase ) return max_prod
335
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''apply_ocr''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'''height''': 42, '''width''': 42} ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) self.assertIsInstance(encoding.words, _lowerCamelCase ) self.assertIsInstance(encoding.boxes, _lowerCamelCase ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' 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 : Tuple = 16 lowercase : List[Any] = 32 def SCREAMING_SNAKE_CASE__ ( __A , __A = 16 , __A = "bert-base-cased" ) -> Any: _snake_case = AutoTokenizer.from_pretrained(__UpperCamelCase ) _snake_case = load_dataset('glue' , 'mrpc' ) def tokenize_function(__A ): # max_length=None => use the model max length (it's actually the default) _snake_case = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _snake_case = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__A ): # 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(__UpperCamelCase , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(__UpperCamelCase , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. _snake_case = DataLoader( tokenized_datasets['train'] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) _snake_case = DataLoader( tokenized_datasets['validation'] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[str]: _snake_case = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case = config['lr'] _snake_case = int(config['num_epochs'] ) _snake_case = int(config['seed'] ) _snake_case = int(config['batch_size'] ) _snake_case = args.model_name_or_path set_seed(__UpperCamelCase ) _snake_case , _snake_case = get_dataloaders(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase , return_dict=__UpperCamelCase ) # Instantiate optimizer _snake_case = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _snake_case = optimizer_cls(params=model.parameters() , lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: _snake_case = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: _snake_case = 1 _snake_case = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _snake_case = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=0 , num_training_steps=__UpperCamelCase , ) else: _snake_case = DummyScheduler(__UpperCamelCase , total_num_steps=__UpperCamelCase , 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. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # We need to keep track of how many total steps we have iterated over _snake_case = 0 # We also need to keep track of the stating epoch so files are named properly _snake_case = 0 # Now we train the model _snake_case = evaluate.load('glue' , 'mrpc' ) _snake_case = 0 _snake_case = {} for epoch in range(__UpperCamelCase , __UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): _snake_case = model(**__UpperCamelCase ) _snake_case = outputs.loss _snake_case = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _snake_case = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case = model(**__UpperCamelCase ) _snake_case = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _snake_case , _snake_case = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: _snake_case = predictions[: len(eval_dataloader.dataset ) - samples_seen] _snake_case = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) _snake_case = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , __UpperCamelCase ) _snake_case = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: _snake_case = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(__UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( ) -> List[Any]: _snake_case = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=__UpperCamelCase , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=__UpperCamelCase , ) parser.add_argument( '--output_dir' , type=__UpperCamelCase , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=__UpperCamelCase , default=__UpperCamelCase , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=__UpperCamelCase , default=3 , help='Number of train epochs.' , ) _snake_case = parser.parse_args() _snake_case = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
42
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a : Tuple = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class __UpperCamelCase ( _lowerCAmelCase , unittest.TestCase ): lowerCamelCase : Optional[Any] =PegasusTokenizer lowerCamelCase : int =PegasusTokenizerFast lowerCamelCase : Optional[Any] =True lowerCamelCase : Union[str, Any] =True def __a ( self ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing a : int = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __a ( self ) -> Optional[Any]: return PegasusTokenizer.from_pretrained("google/pegasus-large" ) def __a ( self , **lowerCAmelCase__ ) -> Any: return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __a ( self , lowerCAmelCase__ ) -> int: return ("This is a test", "This is a test") def __a ( self ) -> int: a : Optional[int] = "</s>" a : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __a ( self ) -> Union[str, Any]: a : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "</s>" ) self.assertEqual(vocab_keys[-1] , "v" ) self.assertEqual(len(_lowerCamelCase ) , 1103 ) def __a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __a ( self ) -> Tuple: a : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) a : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) a : Dict = ( "Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important" " </s> <pad> <pad> <pad>" ) a : Dict = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] a : Tuple = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __a ( self ) -> str: a : Tuple = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word a : List[str] = "<mask_1> To ensure a <mask_2> flow of bank resolutions." a : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] a : Optional[int] = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __a ( self ) -> Dict: a : str = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 a : Any = "To ensure a smooth flow of bank resolutions." a : Optional[int] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] a : Optional[Any] = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __a ( self ) -> Union[str, Any]: a : List[str] = ["This is going to be way too long." * 150, "short example"] a : Any = ["not super long but more than 5 tokens", "tiny"] a : str = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors="pt" ) a : str = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors="pt" ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def __a ( self ) -> Optional[int]: a : int = {"input_ids": [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name="google/bigbird-pegasus-large-arxiv" , revision="ba85d0851d708441f91440d509690f1ab6353415" , ) @require_sentencepiece @require_tokenizers class __UpperCamelCase ( _lowerCAmelCase , unittest.TestCase ): lowerCamelCase : str =PegasusTokenizer lowerCamelCase : Union[str, Any] =PegasusTokenizerFast lowerCamelCase : Any =True lowerCamelCase : str =True def __a ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing a : Optional[Any] = PegasusTokenizer(_lowerCamelCase , offset=0 , mask_token_sent=_lowerCamelCase , mask_token="[MASK]" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __a ( self ) -> Union[str, Any]: return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv" ) def __a ( self , **lowerCAmelCase__ ) -> str: return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __a ( self , lowerCAmelCase__ ) -> Union[str, Any]: return ("This is a test", "This is a test") def __a ( self ) -> Tuple: a : str = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) a : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) a : Any = ( "Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>" " <pad> <pad> <pad>" ) a : Any = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] a : Tuple = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_torch def __a ( self ) -> str: a : Optional[int] = ["This is going to be way too long." * 1000, "short example"] a : Optional[int] = ["not super long but more than 5 tokens", "tiny"] a : str = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors="pt" ) a : str = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors="pt" ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def __a ( self ) -> int: a : Any = ( "This is an example string that is used to test the original TF implementation against the HF" " implementation" ) a : Dict = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
105
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : str = Dict[str, Any] lowerCamelCase : Dict = List[Prediction] @add_end_docstrings(_lowerCAmelCase ) class __lowerCAmelCase (_lowerCAmelCase ): '''simple docstring''' def __init__(self : Dict , *UpperCamelCase : Any , **UpperCamelCase : List[Any] ): '''simple docstring''' super().__init__(*_lowerCamelCase , **_lowerCamelCase ) if self.framework == "tf": raise ValueError(f"The {self.__class__} is only available in PyTorch." ) requires_backends(self , '''vision''' ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase__ (self : Optional[Any] , **UpperCamelCase : str ): '''simple docstring''' lowercase__ = {} if "threshold" in kwargs: lowercase__ = kwargs['''threshold'''] return {}, {}, postprocess_kwargs def __call__(self : List[str] , *UpperCamelCase : List[str] , **UpperCamelCase : Optional[int] ): '''simple docstring''' return super().__call__(*_lowerCamelCase , **_lowerCamelCase ) def UpperCamelCase__ (self : Any , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = load_image(_lowerCamelCase ) lowercase__ = torch.IntTensor([[image.height, image.width]] ) lowercase__ = self.image_processor(images=[image] , return_tensors='''pt''' ) if self.tokenizer is not None: lowercase__ = self.tokenizer(text=inputs['''words'''] , boxes=inputs['''boxes'''] , return_tensors='''pt''' ) lowercase__ = target_size return inputs def UpperCamelCase__ (self : int , UpperCamelCase : str ): '''simple docstring''' lowercase__ = model_inputs.pop('''target_size''' ) lowercase__ = self.model(**_lowerCamelCase ) lowercase__ = outputs.__class__({'''target_size''': target_size, **outputs} ) if self.tokenizer is not None: lowercase__ = model_inputs['''bbox'''] return model_outputs def UpperCamelCase__ (self : int , UpperCamelCase : str , UpperCamelCase : Optional[Any]=0.9 ): '''simple docstring''' lowercase__ = model_outputs['''target_size'''] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. lowercase__ ,lowercase__ = target_size[0].tolist() def unnormalize(UpperCamelCase : Tuple ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) lowercase__ ,lowercase__ = model_outputs['''logits'''].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) lowercase__ = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] lowercase__ = [unnormalize(_lowerCamelCase ) for bbox in model_outputs['''bbox'''].squeeze(0 )] lowercase__ = ['''score''', '''label''', '''box'''] lowercase__ = [dict(zip(_lowerCamelCase , _lowerCamelCase ) ) for vals in zip(scores.tolist() , _lowerCamelCase , _lowerCamelCase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel lowercase__ = self.image_processor.post_process_object_detection(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = raw_annotations[0] lowercase__ = raw_annotation['''scores'''] lowercase__ = raw_annotation['''labels'''] lowercase__ = raw_annotation['''boxes'''] lowercase__ = scores.tolist() lowercase__ = [self.model.config.idalabel[label.item()] for label in labels] lowercase__ = [self._get_bounding_box(_lowerCamelCase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] lowercase__ = ['''score''', '''label''', '''box'''] lowercase__ = [ dict(zip(_lowerCamelCase , _lowerCamelCase ) ) for vals in zip(raw_annotation['''scores'''] , raw_annotation['''labels'''] , raw_annotation['''boxes'''] ) ] return annotation def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError('''The ObjectDetectionPipeline is only available in PyTorch.''' ) lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = box.int().tolist() lowercase__ = { '''xmin''': xmin, '''ymin''': ymin, '''xmax''': xmax, '''ymax''': ymax, } return bbox
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets UpperCAmelCase__ : Any = '\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n' UpperCAmelCase__ : Dict = '\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n' UpperCAmelCase__ : int = '\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "precision": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'precision@10\': 1.0}\n\n' def lowercase_ ( _snake_case ,_snake_case ): return float((preds == labels).mean() ) def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = simple_accuracy(__UpperCamelCase ,__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = float(fa_score(y_true=__UpperCamelCase ,y_pred=__UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : str = en_sentvecs.shape[0] # mean centering SCREAMING_SNAKE_CASE__ : Tuple = en_sentvecs - np.mean(__UpperCamelCase ,axis=0 ) SCREAMING_SNAKE_CASE__ : List[str] = in_sentvecs - np.mean(__UpperCamelCase ,axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = cdist(__UpperCamelCase ,__UpperCamelCase ,"""cosine""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array(range(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ : int = sim.argsort(axis=1 )[:, :10] SCREAMING_SNAKE_CASE__ : int = np.any(preds == actual[:, None] ,axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ (datasets.Metric ): """simple docstring""" def __magic_name__ (self ) -> str: """simple docstring""" if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), """references""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if self.config_name != """cvit-mkb-clsr""" else None , ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_lowerCamelCase , _lowerCamelCase )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_lowerCamelCase , _lowerCamelCase ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_lowerCamelCase , _lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" )
25
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
from __future__ import annotations from typing import Any def __magic_name__ ( __a : Tuple ): '''simple docstring''' if not postfix_notation: return 0 UpperCamelCase__ = {"""+""", """-""", """*""", """/"""} UpperCamelCase__ = [] for token in postfix_notation: if token in operations: UpperCamelCase__ , UpperCamelCase__ = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
244
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def __lowerCamelCase ( A__ ) -> Optional[int]: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" UpperCamelCase = 2 while True: if is_prime(__UpperCamelCase ): yield num num += 1 def __lowerCamelCase ( A__ = 2_000_000 ) -> List[str]: """simple docstring""" return sum(takewhile(lambda A__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(f'''{solution() = }''')
28
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __UpperCamelCase : List[Any] = random.Random() if is_torch_available(): import torch def __SCREAMING_SNAKE_CASE ( A_ , A_=1.0 , A_=None , A_=None ): if rng is None: lowerCAmelCase__ : str = global_rng lowerCAmelCase__ : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : Any ,lowercase_ : List[str] ,lowercase_ : Any=7 ,lowercase_ : Optional[int]=4_0_0 ,lowercase_ : Optional[int]=2_0_0_0 ,lowercase_ : Dict=1 ,lowercase_ : Optional[Any]=0.0 ,lowercase_ : int=1_6_0_0_0 ,lowercase_ : Optional[int]=True ,lowercase_ : Dict=True ,): lowerCAmelCase__ : Any = parent lowerCAmelCase__ : Union[str, Any] = batch_size lowerCAmelCase__ : List[Any] = min_seq_length lowerCAmelCase__ : List[Any] = max_seq_length lowerCAmelCase__ : Any = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCAmelCase__ : List[Any] = feature_size lowerCAmelCase__ : Union[str, Any] = padding_value lowerCAmelCase__ : Dict = sampling_rate lowerCAmelCase__ : Tuple = return_attention_mask lowerCAmelCase__ : str = do_normalize def __lowerCAmelCase ( self : Union[str, Any] ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __lowerCAmelCase ( self : Any ,lowercase_ : Optional[Any]=False ,lowercase_ : int=False ): def _flatten(lowercase_ : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: lowerCAmelCase__ : Any = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size lowerCAmelCase__ : str = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: lowerCAmelCase__ : Any = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE ( _lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowercase__ = ASTFeatureExtractor def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : List[Any] = ASTFeatureExtractionTester(self ) def __lowerCAmelCase ( self : Dict ): lowerCAmelCase__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase__ : List[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 ,1_4_0_0 ,2_0_0 )] lowerCAmelCase__ : Any = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input lowerCAmelCase__ : Optional[int] = feat_extract(speech_inputs[0] ,return_tensors='''np''' ).input_values lowerCAmelCase__ : Optional[int] = feat_extract(np_speech_inputs[0] ,return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase ,_lowerCamelCase ,atol=1E-3 ) ) # Test batched lowerCAmelCase__ : Union[str, Any] = feat_extract(_lowerCamelCase ,padding=_lowerCamelCase ,return_tensors='''np''' ).input_values lowerCAmelCase__ : str = feat_extract(_lowerCamelCase ,padding=_lowerCamelCase ,return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase ,_lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase ,_lowerCamelCase ,atol=1E-3 ) ) # Test 2-D numpy arrays are batched. lowerCAmelCase__ : Optional[int] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] lowerCAmelCase__ : Union[str, Any] = np.asarray(_lowerCamelCase ) lowerCAmelCase__ : Dict = feat_extract(_lowerCamelCase ,return_tensors='''np''' ).input_values lowerCAmelCase__ : Optional[int] = feat_extract(_lowerCamelCase ,return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase ,_lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase ,_lowerCamelCase ,atol=1E-3 ) ) @require_torch def __lowerCAmelCase ( self : Union[str, Any] ): import torch lowerCAmelCase__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ : str = np.random.rand(1_0_0 ).astype(np.floataa ) lowerCAmelCase__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCAmelCase__ : Optional[int] = feature_extractor.pad([{'''input_values''': inputs}] ,return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) lowerCAmelCase__ : Any = feature_extractor.pad([{'''input_values''': inputs}] ,return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowerCAmelCase ( self : Optional[int] ,lowercase_ : Union[str, Any] ): from datasets import load_dataset lowerCAmelCase__ : Union[str, Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,'''clean''' ,split='''validation''' ) # automatic decoding with librispeech lowerCAmelCase__ : Optional[Any] = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : List[str] = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on lowerCAmelCase__ : Tuple = self._load_datasamples(1 ) lowerCAmelCase__ : Any = ASTFeatureExtractor() lowerCAmelCase__ : str = feature_extractor(_lowerCamelCase ,return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape ,(1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] ,_lowerCamelCase ,atol=1E-4 ) )
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def __lowercase ( ): UpperCamelCase_ : List[Any] = 10 UpperCamelCase_ : Optional[Any] = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) UpperCamelCase_ : str = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(__UpperCamelCase ) ), } , features=__UpperCamelCase , ) return dataset @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[str] , lowerCamelCase : Union[str, Any] ): UpperCamelCase_ : List[str] = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=__UpperCamelCase ) return filename # FILE_CONTENT + files a_ = '\\n Text data.\n Second line of data.' @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[Any] ): UpperCamelCase_ : Any = tmp_path_factory.mktemp('data' ) / 'file.txt' UpperCamelCase_ : List[str] = FILE_CONTENT with open(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase ) return filename @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[Any] ): import bza UpperCamelCase_ : str = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' UpperCamelCase_ : Union[str, Any] = bytes(__UpperCamelCase , 'utf-8' ) with bza.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[int] ): import gzip UpperCamelCase_ : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) UpperCamelCase_ : List[str] = bytes(__UpperCamelCase , 'utf-8' ) with gzip.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple ): if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCamelCase_ : str = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' UpperCamelCase_ : List[str] = bytes(__UpperCamelCase , 'utf-8' ) with lza.frame.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] ): if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCamelCase_ : Dict = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(__UpperCamelCase , 'w' ) as archive: archive.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict ): import tarfile UpperCamelCase_ : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(__UpperCamelCase , 'w' ) as f: f.add(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any ): import lzma UpperCamelCase_ : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' UpperCamelCase_ : int = bytes(__UpperCamelCase , 'utf-8' ) with lzma.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[int] , lowerCamelCase : str ): import zipfile UpperCamelCase_ : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any ): if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCamelCase_ : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' UpperCamelCase_ : int = bytes(__UpperCamelCase , 'utf-8' ) with zstd.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Dict ): UpperCamelCase_ : Any = tmp_path_factory.mktemp('data' ) / 'file.xml' UpperCamelCase_ : List[Any] = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase ) return filename a_ = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] a_ = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] a_ = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } a_ = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] a_ = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope='session' ) def __lowercase ( ): return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any ): UpperCamelCase_ : List[str] = datasets.Dataset.from_dict(__UpperCamelCase ) UpperCamelCase_ : int = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(__UpperCamelCase ) ) as con: UpperCamelCase_ : int = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(__UpperCamelCase , 'w' , newline='' ) as f: UpperCamelCase_ : str = csv.DictWriter(__UpperCamelCase , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[Any] ): UpperCamelCase_ : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(__UpperCamelCase , 'w' , newline='' ) as f: UpperCamelCase_ : int = csv.DictWriter(__UpperCamelCase , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : str ): import bza UpperCamelCase_ : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(__UpperCamelCase , 'rb' ) as f: UpperCamelCase_ : Optional[Any] = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__UpperCamelCase , 'wb' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : str , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int] ): UpperCamelCase_ : str = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int ): UpperCamelCase_ : Optional[int] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(__UpperCamelCase , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] ): UpperCamelCase_ : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Dict ): UpperCamelCase_ : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) UpperCamelCase_ : Optional[Any] = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(__UpperCamelCase , 'wb' ) as f: UpperCamelCase_ : Optional[Any] = pq.ParquetWriter(__UpperCamelCase , schema=__UpperCamelCase ) UpperCamelCase_ : int = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__UpperCamelCase ) )] for k in DATA[0]} , schema=__UpperCamelCase ) writer.write_table(__UpperCamelCase ) writer.close() return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : int ): UpperCamelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) UpperCamelCase_ : Dict = {'data': DATA} with open(__UpperCamelCase , 'w' ) as f: json.dump(__UpperCamelCase , __UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] ): UpperCamelCase_ : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) UpperCamelCase_ : int = {'data': DATA_DICT_OF_LISTS} with open(__UpperCamelCase , 'w' ) as f: json.dump(__UpperCamelCase , __UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[int] ): UpperCamelCase_ : str = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(__UpperCamelCase , 'w' ) as f: for item in DATA: f.write(json.dumps(__UpperCamelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] ): UpperCamelCase_ : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(__UpperCamelCase , 'w' ) as f: for item in DATA: f.write(json.dumps(__UpperCamelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : int ): UpperCamelCase_ : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(__UpperCamelCase , 'w' ) as f: for item in DATA_312: f.write(json.dumps(__UpperCamelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(__UpperCamelCase , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(__UpperCamelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : str , lowerCamelCase : Optional[Any] ): import gzip UpperCamelCase_ : int = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(__UpperCamelCase , 'rb' ) as orig_file: with gzip.open(__UpperCamelCase , 'wb' ) as zipped_file: zipped_file.writelines(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : List[Any] ): import gzip UpperCamelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(__UpperCamelCase , 'rb' ) as orig_file: with gzip.open(__UpperCamelCase , 'wb' ) as zipped_file: zipped_file.writelines(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : Dict , lowerCamelCase : int ): UpperCamelCase_ : Dict = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[Any] , lowerCamelCase : str , lowerCamelCase : Optional[int] , lowerCamelCase : Any ): UpperCamelCase_ : str = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.join('nested' , os.path.basename(__UpperCamelCase ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : str , lowerCamelCase : Optional[Any] ): UpperCamelCase_ : Optional[int] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Dict ): UpperCamelCase_ : str = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(__UpperCamelCase , 'w' ) as f: f.add(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) f.add(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : str , lowerCamelCase : Dict , lowerCamelCase : Tuple ): UpperCamelCase_ : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(__UpperCamelCase , 'w' ) as f: f.add(__UpperCamelCase , arcname=os.path.join('nested' , os.path.basename(__UpperCamelCase ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : Union[str, Any] = ['0', '1', '2', '3'] UpperCamelCase_ : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(__UpperCamelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[Any] ): UpperCamelCase_ : Tuple = ['0', '1', '2', '3'] UpperCamelCase_ : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(__UpperCamelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : List[str] = ['0', '1', '2', '3'] UpperCamelCase_ : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(__UpperCamelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] ): UpperCamelCase_ : int = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Tuple , lowerCamelCase : List[str] ): UpperCamelCase_ : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) f.write(__UpperCamelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCamelCase ) ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Optional[int] ): UpperCamelCase_ : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename('unsupported.ext' ) ) f.write(__UpperCamelCase , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : List[Any] ): UpperCamelCase_ : int = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) UpperCamelCase_ : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(__UpperCamelCase , 'w' , encoding='utf-8' ) as f: f.write(__UpperCamelCase ) return path @pytest.fixture(scope='session' ) def __lowercase ( ): return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def __lowercase ( ): return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : int , lowerCamelCase : Tuple ): UpperCamelCase_ : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(__UpperCamelCase , 'w' ) as f: f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ) ) f.write(__UpperCamelCase , arcname=os.path.basename(__UpperCamelCase ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def __lowercase ( lowerCamelCase : Optional[Any] ): UpperCamelCase_ : List[str] = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) return data_dir
175
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) __A = 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 : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __lowercase ( _lowerCAmelCase ): lowerCamelCase : torch.FloatTensor lowerCamelCase : torch.FloatTensor class __lowercase ( _lowerCAmelCase , _lowerCAmelCase ): lowerCamelCase : List[str] = 1 @register_to_config def __init__(self , A = 2_0_0_0 , A = 0.15 , A = 0.01 , A = 1_3_4_8.0 , A = 1E-5 , A = 1 , ): lowerCamelCase_ : Any = sigma_max # setable values lowerCamelCase_ : Optional[int] = None self.set_sigmas(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase__ (self , A , A = None ): return sample def UpperCAmelCase__ (self , A , A = None , A = None ): lowerCamelCase_ : int = sampling_eps if sampling_eps is not None else self.config.sampling_eps lowerCamelCase_ : Dict = torch.linspace(1 , _lowerCamelCase , _lowerCamelCase , device=_lowerCamelCase ) def UpperCAmelCase__ (self , A , A = None , A = None , A = None ): lowerCamelCase_ : Any = sigma_min if sigma_min is not None else self.config.sigma_min lowerCamelCase_ : Dict = sigma_max if sigma_max is not None else self.config.sigma_max lowerCamelCase_ : Optional[int] = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase_ : Dict = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) lowerCamelCase_ : Tuple = torch.exp(torch.linspace(math.log(_lowerCamelCase ) , math.log(_lowerCamelCase ) , _lowerCamelCase ) ) lowerCamelCase_ : Optional[Any] = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def UpperCAmelCase__ (self , A , A ): return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def UpperCAmelCase__ (self , A , A , A , A = None , A = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) lowerCamelCase_ : Union[str, Any] = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) lowerCamelCase_ : Any = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda lowerCamelCase_ : List[str] = timesteps.to(self.discrete_sigmas.device ) lowerCamelCase_ : str = self.discrete_sigmas[timesteps].to(sample.device ) lowerCamelCase_ : Optional[int] = self.get_adjacent_sigma(_lowerCamelCase , _lowerCamelCase ).to(sample.device ) lowerCamelCase_ : int = torch.zeros_like(_lowerCamelCase ) lowerCamelCase_ : str = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods lowerCamelCase_ : int = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): lowerCamelCase_ : List[str] = diffusion.unsqueeze(-1 ) lowerCamelCase_ : Tuple = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of lowerCamelCase_ : Optional[int] = randn_tensor( sample.shape , layout=sample.layout , generator=_lowerCamelCase , device=sample.device , dtype=sample.dtype ) lowerCamelCase_ : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? lowerCamelCase_ : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=_lowerCamelCase , prev_sample_mean=_lowerCamelCase ) def UpperCAmelCase__ (self , A , A , A = None , A = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction lowerCamelCase_ : Optional[Any] = randn_tensor(sample.shape , layout=sample.layout , generator=_lowerCamelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr lowerCamelCase_ : Any = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() lowerCamelCase_ : Optional[Any] = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() lowerCamelCase_ : Union[str, Any] = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 lowerCamelCase_ : Optional[int] = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term lowerCamelCase_ : int = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): lowerCamelCase_ : Dict = step_size.unsqueeze(-1 ) lowerCamelCase_ : Tuple = sample + step_size * model_output lowerCamelCase_ : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowerCamelCase ) def UpperCAmelCase__ (self , A , A , A , ): lowerCamelCase_ : Union[str, Any] = timesteps.to(original_samples.device ) lowerCamelCase_ : List[Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] lowerCamelCase_ : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(_lowerCamelCase ) * sigmas[:, None, None, None] ) lowerCamelCase_ : Optional[Any] = noise + original_samples return noisy_samples def __len__(self ): return self.config.num_train_timesteps
318
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
from collections import Counter from timeit import timeit def UpperCamelCase ( lowerCAmelCase__ = "" , ): '''simple docstring''' return sum(c % 2 for c in Counter(input_str.replace(''' ''' , '''''' ).lower() ).values() ) < 2 def UpperCamelCase ( lowerCAmelCase__ = "" ): '''simple docstring''' if len(__UpperCamelCase ) == 0: return True lowercase = input_str.replace(''' ''' , '''''' ).lower() # character_freq_dict: Stores the frequency of every character in the input string lowercase = {} for character in lower_case_input_str: lowercase = character_freq_dict.get(__UpperCamelCase , 0 ) + 1 lowercase = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def UpperCamelCase ( lowerCAmelCase__ = "" ): '''simple docstring''' print('''\nFor string = ''' , __UpperCamelCase , ''':''' ) print( '''> can_string_be_rearranged_as_palindrome_counter()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome_counter(__UpperCamelCase ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome_counter(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) print( '''> can_string_be_rearranged_as_palindrome()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome(__UpperCamelCase ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) if __name__ == "__main__": lowercase__ :List[str] = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) lowercase__ :Dict = can_string_be_rearranged_as_palindrome_counter(check_str) print(F'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
101
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
'''simple docstring''' import os def a__ ( a__ = "matrix.txt" ): """simple docstring""" with open(os.path.join(os.path.dirname(a__ ) , a__ ) ) as in_file: __SCREAMING_SNAKE_CASE = in_file.read() __SCREAMING_SNAKE_CASE = [[int(a__ ) for cell in row.split(""",""" )] for row in data.strip().splitlines()] __SCREAMING_SNAKE_CASE = [[0 for cell in row] for row in grid] __SCREAMING_SNAKE_CASE = len(grid[0] ) __SCREAMING_SNAKE_CASE = [[0 for i in range(a__ )] for j in range(a__ )] __SCREAMING_SNAKE_CASE = grid[0][0] for i in range(1 , a__ ): __SCREAMING_SNAKE_CASE = grid[0][i] + dp[0][i - 1] for i in range(1 , a__ ): __SCREAMING_SNAKE_CASE = grid[i][0] + dp[i - 1][0] for i in range(1 , a__ ): for j in range(1 , a__ ): __SCREAMING_SNAKE_CASE = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"""{solution() = }""")
267
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
1
'''simple docstring''' import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : int = 32 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Union[int, float] = 1 / 255 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073] , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711] , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : int=30 , __SCREAMING_SNAKE_CASE : Dict=400 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size if size is not None else {"""shortest_edge""": 288} __SCREAMING_SNAKE_CASE = size_divisor __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = do_center_crop __SCREAMING_SNAKE_CASE = image_mean __SCREAMING_SNAKE_CASE = image_std __SCREAMING_SNAKE_CASE = do_pad __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = min_resolution __SCREAMING_SNAKE_CASE = max_resolution def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple=False ) -> Optional[Any]: """simple docstring""" if not batched: __SCREAMING_SNAKE_CASE = self.size["""shortest_edge"""] __SCREAMING_SNAKE_CASE = image_inputs[0] if isinstance(__SCREAMING_SNAKE_CASE , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2] __SCREAMING_SNAKE_CASE = size / min(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if h < w: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = size, scale * w else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = scale * h, size __SCREAMING_SNAKE_CASE = int((1_333 / 800) * size ) if max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) > max_size: __SCREAMING_SNAKE_CASE = max_size / max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = newh * scale __SCREAMING_SNAKE_CASE = neww * scale __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = int(newh + 0.5 ), int(neww + 0.5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: __SCREAMING_SNAKE_CASE = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0] __SCREAMING_SNAKE_CASE = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = BridgeTowerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = BridgeTowerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 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""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size_divisor""" ) ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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, ) , )
267
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import _LazyModule UpperCAmelCase : Optional[Any] = {'tokenization_tapex': ['TapexTokenizer']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
267
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
1
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 UpperCAmelCase : Optional[int] = get_tests_dir('fixtures') UpperCAmelCase : Any = get_tests_dir('fixtures/dummy_feature_extractor_config.json') UpperCAmelCase : Any = get_tests_dir('fixtures/dummy-config.json') class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0 def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ).to_dict() config_dict.pop("""feature_extractor_type""" ) __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor(**__SCREAMING_SNAKE_CASE ) # save in new folder model_config.save_pretrained(__SCREAMING_SNAKE_CASE ) config.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , """bert-base is not a local folder and is not a valid model identifier""" ): __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained("""bert-base""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , revision="""aaaaaa""" ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: """simple docstring""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" try: AutoConfig.register("""custom""" , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__SCREAMING_SNAKE_CASE ): AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API __SCREAMING_SNAKE_CASE = CustomFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = True try: AutoConfig.register("""custom""" , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(not hasattr(__SCREAMING_SNAKE_CASE , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
267
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
1
'''simple docstring''' def a__ ( a__ = 1_00_00_00 ): """simple docstring""" __SCREAMING_SNAKE_CASE = set(range(3 , a__ , 2 ) ) primes.add(2 ) for p in range(3 , a__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , a__ , a__ ) ) ) __SCREAMING_SNAKE_CASE = [float(a__ ) for n in range(limit + 1 )] for p in primes: for n in range(a__ , limit + 1 , a__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f"""{solution() = }""")
267
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
1
'''simple docstring''' import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_attention_heads""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_encoder_blocks""" ) ) class lowerCAmelCase__ : """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[str]=13 , __SCREAMING_SNAKE_CASE : Dict=64 , __SCREAMING_SNAKE_CASE : Any=3 , __SCREAMING_SNAKE_CASE : int=4 , __SCREAMING_SNAKE_CASE : Dict=[2, 2, 2, 2] , __SCREAMING_SNAKE_CASE : Any=[8, 4, 2, 1] , __SCREAMING_SNAKE_CASE : int=[16, 32, 64, 128] , __SCREAMING_SNAKE_CASE : List[Any]=[1, 4, 8, 16] , __SCREAMING_SNAKE_CASE : int=[1, 2, 4, 8] , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Any=None , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = num_encoder_blocks __SCREAMING_SNAKE_CASE = sr_ratios __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = hidden_sizes __SCREAMING_SNAKE_CASE = downsampling_rates __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = SegformerModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) lowerCAmelCase__ = ( { "feature-extraction": SegformerModel, "image-classification": SegformerForImageClassification, "image-segmentation": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = SegformerModelTester(self ) __SCREAMING_SNAKE_CASE = SegformerConfigTester(self , config_class=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*__SCREAMING_SNAKE_CASE ) @unittest.skip("""SegFormer does not use inputs_embeds""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" pass @unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" pass def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs.attentions __SCREAMING_SNAKE_CASE = sum(self.model_tester.depths ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first attentions (first block, first layer) __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // 4) ** 2 __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // 32) ** 2 __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + 1 , len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first attentions (first block, first layer) __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // 4) ** 2 __SCREAMING_SNAKE_CASE = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" def check_hidden_states_output(__SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs.hidden_states __SCREAMING_SNAKE_CASE = self.model_tester.num_encoder_blocks self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: """simple docstring""" if not self.model_tester.is_training: return __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(__SCREAMING_SNAKE_CASE ): continue __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() __SCREAMING_SNAKE_CASE = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" pass @slow def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = SegformerModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__SCREAMING_SNAKE_CASE , align=__SCREAMING_SNAKE_CASE , do_random_crop=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__SCREAMING_SNAKE_CASE , align=__SCREAMING_SNAKE_CASE , do_random_crop=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation.from_pretrained( """nvidia/segformer-b1-finetuned-cityscapes-1024-1024""" ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-1 ) ) @slow def UpperCAmelCase__ ( self : Dict ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__SCREAMING_SNAKE_CASE , align=__SCREAMING_SNAKE_CASE , do_random_crop=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = outputs.logits.detach().cpu() __SCREAMING_SNAKE_CASE = image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE , target_sizes=[(500, 300)] ) __SCREAMING_SNAKE_CASE = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Size((128, 128) ) self.assertEqual(segmentation[0].shape , __SCREAMING_SNAKE_CASE )
267
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
1
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. UpperCAmelCase : Tuple = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def a__ ( a__ ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(a__ ) def a__ ( a__ ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main __SCREAMING_SNAKE_CASE = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(a__ , id=a__ )
267
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' def a__ ( a__ = 1_00_00_00 ): """simple docstring""" __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = {1: 1} for inputa in range(2 , a__ ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: __SCREAMING_SNAKE_CASE = (3 * number) + 1 counter += 1 if inputa not in counters: __SCREAMING_SNAKE_CASE = counter if counter > pre_counter: __SCREAMING_SNAKE_CASE = inputa __SCREAMING_SNAKE_CASE = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : Any ) -> Optional[int]: """simple docstring""" pass @is_pipeline_test @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @require_torch def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , ) __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __SCREAMING_SNAKE_CASE = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}], [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}], ] , ) __SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], ] , ) @require_tf def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""" ) __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __SCREAMING_SNAKE_CASE = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}] , ) __SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], [ {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": 0.333, """label""": ANY(__SCREAMING_SNAKE_CASE )}, ], ] , ) @slow @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , ) # This is an image of 2 cats with remotes and no planes __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __SCREAMING_SNAKE_CASE = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) __SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , ) @slow @require_tf def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""" ) # This is an image of 2 cats with remotes and no planes __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __SCREAMING_SNAKE_CASE = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) __SCREAMING_SNAKE_CASE = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , )
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = ["pixel_values"] def __init__( self : str , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Dict[str, int]] = None , __SCREAMING_SNAKE_CASE : PILImageResampling = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Union[int, float] = 1 / 255 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , **__SCREAMING_SNAKE_CASE : Optional[int] , ) -> None: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = size if size is not None else {"""shortest_edge""": 256} __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = resample __SCREAMING_SNAKE_CASE = do_center_crop __SCREAMING_SNAKE_CASE = crop_size __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Dict[str, int] , __SCREAMING_SNAKE_CASE : PILImageResampling = PILImageResampling.BICUBIC , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : List[str] , ) -> np.ndarray: """simple docstring""" __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __SCREAMING_SNAKE_CASE = get_resize_output_image_size(__SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=__SCREAMING_SNAKE_CASE ) return resize(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Dict[str, int] , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Any , ) -> np.ndarray: """simple docstring""" __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE ) return center_crop(__SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : str ) -> np.ndarray: """simple docstring""" return rescale(__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Union[float, List[float]] , __SCREAMING_SNAKE_CASE : Union[float, List[float]] , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Dict , ) -> np.ndarray: """simple docstring""" return normalize(__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : ImageInput , __SCREAMING_SNAKE_CASE : Optional[bool] = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : PILImageResampling = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : Optional[bool] = None , __SCREAMING_SNAKE_CASE : Optional[float] = None , __SCREAMING_SNAKE_CASE : Optional[bool] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , __SCREAMING_SNAKE_CASE : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__SCREAMING_SNAKE_CASE : Dict , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE = size if size is not None else self.size __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE = do_center_crop if do_center_crop is not None else self.do_center_crop __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else self.crop_size __SCREAMING_SNAKE_CASE = get_size_dict(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE = 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.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE = [to_numpy_array(__SCREAMING_SNAKE_CASE ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE = [self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: __SCREAMING_SNAKE_CASE = [self.center_crop(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(image=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: __SCREAMING_SNAKE_CASE = [self.normalize(image=__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for image in images] __SCREAMING_SNAKE_CASE = {"""pixel_values""": images} return BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE )
267
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : Any = { 'naver-clova-ix/donut-base': 'https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json', # See all Donut models at https://huggingface.co/models?filter=donut-swin } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "donut-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]=224 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : List[Any]=3 , __SCREAMING_SNAKE_CASE : Union[str, Any]=96 , __SCREAMING_SNAKE_CASE : Union[str, Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : str=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : List[str]=7 , __SCREAMING_SNAKE_CASE : List[str]=4.0 , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : List[Any]=0.0 , __SCREAMING_SNAKE_CASE : Any=0.0 , __SCREAMING_SNAKE_CASE : Tuple=0.1 , __SCREAMING_SNAKE_CASE : int="gelu" , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : Optional[Any]=1E-5 , **__SCREAMING_SNAKE_CASE : str , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) )
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {'tokenizer_file': 'tokenizer.json'} UpperCAmelCase : Union[str, Any] = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = ["input_ids", "attention_mask"] lowerCAmelCase__ = None def __init__( self : str , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : int="<unk>" , __SCREAMING_SNAKE_CASE : Dict="<s>" , __SCREAMING_SNAKE_CASE : str="</s>" , __SCREAMING_SNAKE_CASE : Dict="<pad>" , __SCREAMING_SNAKE_CASE : List[Any]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , **__SCREAMING_SNAKE_CASE : Tuple , ) -> int: """simple docstring""" super().__init__( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __SCREAMING_SNAKE_CASE ) != add_prefix_space: __SCREAMING_SNAKE_CASE = getattr(__SCREAMING_SNAKE_CASE , pre_tok_state.pop("""type""" ) ) __SCREAMING_SNAKE_CASE = add_prefix_space __SCREAMING_SNAKE_CASE = pre_tok_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = add_prefix_space def UpperCAmelCase__ ( self : Optional[int] , *__SCREAMING_SNAKE_CASE : Any , **__SCREAMING_SNAKE_CASE : Dict ) -> BatchEncoding: """simple docstring""" __SCREAMING_SNAKE_CASE = kwargs.get("""is_split_into_words""" , __SCREAMING_SNAKE_CASE ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with' """ pretokenized inputs.""" ) return super()._batch_encode_plus(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , *__SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Any ) -> BatchEncoding: """simple docstring""" __SCREAMING_SNAKE_CASE = kwargs.get("""is_split_into_words""" , __SCREAMING_SNAKE_CASE ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with' """ pretokenized inputs.""" ) return super()._encode_plus(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE ) return tuple(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : "Conversation" ) -> List[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) + [self.eos_token_id] ) if len(__SCREAMING_SNAKE_CASE ) > self.model_max_length: __SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] return input_ids
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : List[str] = { 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "git_vision_model" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : str=768 , __SCREAMING_SNAKE_CASE : List[Any]=3_072 , __SCREAMING_SNAKE_CASE : int=12 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : List[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=16 , __SCREAMING_SNAKE_CASE : List[str]="quick_gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , **__SCREAMING_SNAKE_CASE : Dict , ) -> Optional[int]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = hidden_act @classmethod def UpperCAmelCase__ ( cls : Tuple , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": __SCREAMING_SNAKE_CASE = 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 lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "git" def __init__( self : int , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : int=30_522 , __SCREAMING_SNAKE_CASE : Any=768 , __SCREAMING_SNAKE_CASE : int=6 , __SCREAMING_SNAKE_CASE : int=12 , __SCREAMING_SNAKE_CASE : str=3_072 , __SCREAMING_SNAKE_CASE : str="gelu" , __SCREAMING_SNAKE_CASE : List[str]=0.1 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : int=1_024 , __SCREAMING_SNAKE_CASE : Tuple=0.02 , __SCREAMING_SNAKE_CASE : str=1E-12 , __SCREAMING_SNAKE_CASE : Dict=0 , __SCREAMING_SNAKE_CASE : str="absolute" , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : str=101 , __SCREAMING_SNAKE_CASE : Union[str, Any]=102 , __SCREAMING_SNAKE_CASE : str=None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> Optional[int]: """simple docstring""" super().__init__(bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if vision_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) __SCREAMING_SNAKE_CASE = GitVisionConfig(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = tie_word_embeddings __SCREAMING_SNAKE_CASE = num_image_with_embedding __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' def a__ ( a__ ): """simple docstring""" return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FunnelTokenizer lowerCAmelCase__ = FunnelTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" super().setUp() __SCREAMING_SNAKE_CASE = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def UpperCAmelCase__ ( self : List[str] , **__SCREAMING_SNAKE_CASE : Tuple ) -> int: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = """UNwant\u00E9d,running""" __SCREAMING_SNAKE_CASE = """unwanted, running""" return input_text, output_text def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [7, 4, 5, 10, 8, 9] ) def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: __SCREAMING_SNAKE_CASE = tokenizer("""UNwant\u00E9d,running""" ) __SCREAMING_SNAKE_CASE = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) __SCREAMING_SNAKE_CASE = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = SwinConfig(image_size=1_92 ) if "base" in model_name: __SCREAMING_SNAKE_CASE = 6 __SCREAMING_SNAKE_CASE = 1_28 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (4, 8, 16, 32) elif "large" in model_name: __SCREAMING_SNAKE_CASE = 12 __SCREAMING_SNAKE_CASE = 1_92 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (6, 12, 24, 48) else: raise ValueError("""Model not supported, only supports base and large variants""" ) __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = num_heads return config def a__ ( a__ ): """simple docstring""" if "encoder.mask_token" in name: __SCREAMING_SNAKE_CASE = name.replace("""encoder.mask_token""" , """embeddings.mask_token""" ) if "encoder.patch_embed.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("""encoder.patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "encoder.patch_embed.norm" in name: __SCREAMING_SNAKE_CASE = name.replace("""encoder.patch_embed.norm""" , """embeddings.norm""" ) if "attn.proj" in name: __SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": __SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "encoder.norm.bias": __SCREAMING_SNAKE_CASE = """layernorm.bias""" if "decoder" in name: pass else: __SCREAMING_SNAKE_CASE = """swin.""" + name return name def a__ ( a__ , a__ ): """simple docstring""" for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = orig_state_dict.pop(a__ ) if "attn_mask" in key: pass elif "qkv" in key: __SCREAMING_SNAKE_CASE = key.split(""".""" ) __SCREAMING_SNAKE_CASE = int(key_split[2] ) __SCREAMING_SNAKE_CASE = int(key_split[4] ) __SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __SCREAMING_SNAKE_CASE = val[:dim, :] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE = val[-dim:, :] else: __SCREAMING_SNAKE_CASE = val[ :dim ] __SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE = val[ -dim: ] else: __SCREAMING_SNAKE_CASE = val return orig_state_dict def a__ ( a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" )["""model"""] __SCREAMING_SNAKE_CASE = get_swin_config(a__ ) __SCREAMING_SNAKE_CASE = SwinForMaskedImageModeling(a__ ) model.eval() __SCREAMING_SNAKE_CASE = convert_state_dict(a__ , a__ ) model.load_state_dict(a__ ) __SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" __SCREAMING_SNAKE_CASE = ViTImageProcessor(size={"""height""": 1_92, """width""": 1_92} ) __SCREAMING_SNAKE_CASE = Image.open(requests.get(a__ , stream=a__ ).raw ) __SCREAMING_SNAKE_CASE = image_processor(images=a__ , return_tensors="""pt""" ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**a__ ).logits print(outputs.keys() ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(a__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(a__ ) if push_to_hub: print(F'Pushing model and image processor for {model_name} to hub' ) model.push_to_hub(F'microsoft/{model_name}' ) image_processor.push_to_hub(F'microsoft/{model_name}' ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='swin-base-simmim-window6-192', type=str, choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'], help='Name of the Swin SimMIM model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth', type=str, help='Path to the original PyTorch checkpoint (.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.' ) UpperCAmelCase : Tuple = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' import math def a__ ( a__ = 1_00 ): """simple docstring""" __SCREAMING_SNAKE_CASE = sum(i * i for i in range(1 , n + 1 ) ) __SCREAMING_SNAKE_CASE = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''simple docstring''' from math import factorial def a__ ( a__ = 1_00 ): """simple docstring""" return sum(map(a__ , str(factorial(a__ ) ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase : int = logging.get_logger(__name__) def a__ ( a__ , a__ ): """simple docstring""" try: with open(a__ , """rb""" ) as flax_state_f: __SCREAMING_SNAKE_CASE = from_bytes(a__ , flax_state_f.read() ) except UnpicklingError as e: try: with open(a__ ) as f: if f.read().startswith("""version""" ): raise OSError( """You seem to have cloned a repository without having git-lfs installed. Please""" """ install git-lfs and run `git lfs install` followed by `git lfs pull` in the""" """ folder you cloned.""" ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(a__ , a__ ) def a__ ( a__ , a__ ): """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( """Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise # check if we have bf16 weights __SCREAMING_SNAKE_CASE = flatten_dict(jax.tree_util.tree_map(lambda a__ : x.dtype == jnp.bfloataa , a__ ) ).values() if any(a__ ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( """Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` """ """before loading those in PyTorch model.""" ) __SCREAMING_SNAKE_CASE = jax.tree_util.tree_map( lambda a__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , a__ ) __SCREAMING_SNAKE_CASE = """""" __SCREAMING_SNAKE_CASE = flatten_dict(a__ , sep=""".""" ) __SCREAMING_SNAKE_CASE = pt_model.state_dict() # keep track of unexpected & missing keys __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): __SCREAMING_SNAKE_CASE = flax_key_tuple.split(""".""" ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: __SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["""weight"""] __SCREAMING_SNAKE_CASE = jnp.transpose(a__ , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": __SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["""weight"""] __SCREAMING_SNAKE_CASE = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": __SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["""weight"""] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(a__ ): __SCREAMING_SNAKE_CASE = ( flax_key_tuple_string.replace("""_0""" , """.0""" ) .replace("""_1""" , """.1""" ) .replace("""_2""" , """.2""" ) .replace("""_3""" , """.3""" ) .replace("""_4""" , """.4""" ) .replace("""_5""" , """.5""" ) .replace("""_6""" , """.6""" ) .replace("""_7""" , """.7""" ) .replace("""_8""" , """.8""" ) .replace("""_9""" , """.9""" ) ) __SCREAMING_SNAKE_CASE = """.""".join(a__ ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' F'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict __SCREAMING_SNAKE_CASE = np.asarray(a__ ) if not isinstance(a__ , np.ndarray ) else flax_tensor __SCREAMING_SNAKE_CASE = torch.from_numpy(a__ ) # remove from missing keys missing_keys.remove(a__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(a__ ) pt_model.load_state_dict(a__ ) # re-transform missing_keys to list __SCREAMING_SNAKE_CASE = list(a__ ) if len(a__ ) > 0: logger.warning( """Some weights of the Flax model were not used when initializing the PyTorch model""" F' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' F' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' """ (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This""" F' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' """ to be exactly identical (e.g. initializing a BertForSequenceClassification model from a""" """ FlaxBertForSequenceClassification model).""" ) if len(a__ ) > 0: logger.warning( F'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' F' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' """ use it for predictions and inference.""" ) return pt_model
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0 @slow def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Check that tokenizer_type ≠ model_type __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__SCREAMING_SNAKE_CASE , """vocab.txt""" ) ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , tokenizer_type="""bert""" , use_fast=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__SCREAMING_SNAKE_CASE , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__SCREAMING_SNAKE_CASE , """merges.txt""" ) ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , tokenizer_type="""gpt2""" , use_fast=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @require_tokenizers def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__SCREAMING_SNAKE_CASE , """vocab.txt""" ) ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , tokenizer_type="""bert""" ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__SCREAMING_SNAKE_CASE , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__SCREAMING_SNAKE_CASE , """merges.txt""" ) ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , tokenizer_type="""gpt2""" ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE ): AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" ) @require_tokenizers def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: __SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , __SCREAMING_SNAKE_CASE ) else: self.assertEqual(tokenizer.do_lower_case , __SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ): __SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" ) def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = TOKENIZER_MAPPING.values() __SCREAMING_SNAKE_CASE = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(__SCREAMING_SNAKE_CASE ) @require_tokenizers def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , __SCREAMING_SNAKE_CASE ) @require_tokenizers def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """Hello, world. How are you?""" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertEqual("""[UNK]""" , tokens[0] ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertEqual("""[UNK]""" , tokens[0] ) @require_tokenizers def UpperCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" ) self.assertEqual(type(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 30_000 ) self.assertEqual(tokenizer.unk_token , """[UNK]""" ) self.assertEqual(tokenizer.padding_side , """right""" ) self.assertEqual(tokenizer.truncation_side , """right""" ) def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""ctrl""" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = get_tokenizer_config("""bert-base-cased""" ) __SCREAMING_SNAKE_CASE = config.pop("""_commit_hash""" , __SCREAMING_SNAKE_CASE ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(__SCREAMING_SNAKE_CASE , {"""do_lower_case""": False} ) # This model does not have a tokenizer_config so we get back an empty dict. __SCREAMING_SNAKE_CASE = get_tokenizer_config(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(__SCREAMING_SNAKE_CASE , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = get_tokenizer_config(__SCREAMING_SNAKE_CASE ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" try: AutoConfig.register("""custom""" , __SCREAMING_SNAKE_CASE ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__SCREAMING_SNAKE_CASE ): AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CustomTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" try: AutoConfig.register("""custom""" , __SCREAMING_SNAKE_CASE ) # Can register in two steps AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , fast_tokenizer_class=__SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( __SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE , fast_tokenizer_class=__SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__SCREAMING_SNAKE_CASE ): AutoTokenizer.register(__SCREAMING_SNAKE_CASE , fast_tokenizer_class=__SCREAMING_SNAKE_CASE ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained(__SCREAMING_SNAKE_CASE ) bert_tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CustomTokenizerFast.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) @require_tokenizers def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = False class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = NewTokenizer lowerCAmelCase__ = False try: AutoConfig.register("""custom""" , __SCREAMING_SNAKE_CASE ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , fast_tokenizer_class=__SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=__SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertTrue(tokenizer.special_attribute_present ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , """bert-base is not a local folder and is not a valid model identifier""" ): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""bert-base""" ) def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , revision="""aaaaaa""" ) def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1