code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
141
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever lowerCamelCase__ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[Any] , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Optional[Any]=None ): '''simple docstring''' super().__init__( __lowercase , question_encoder_tokenizer=__lowercase , generator_tokenizer=__lowercase , index=__lowercase , init_retrieval=__lowercase , ) __a = None def UpperCamelCase_ ( self : List[Any] , __lowercase : int ): '''simple docstring''' logger.info("""initializing retrieval""" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("""dist initialized""" ) # needs to be set manually __a = self._infer_socket_ifname() # avoid clash with the NCCL port __a = str(distributed_port + 1 ) __a = dist.new_group(ranks=__lowercase , backend="""gloo""" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("""dist not initialized / main""" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self : int , __lowercase : List[str] , __lowercase : int , __lowercase : List[str]=torch.floataa ): '''simple docstring''' __a = torch.empty(__lowercase , dtype=__lowercase ) dist.scatter(__lowercase , src=0 , scatter_list=__lowercase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = psutil.net_if_addrs() # a hacky way to deal with varying network interface names __a = next((addr for addr in addrs if addr.startswith("""e""" )) , __lowercase ) return ifname def UpperCamelCase_ ( self : int , __lowercase : np.ndarray , __lowercase : int ): '''simple docstring''' # single GPU training if not dist.is_initialized(): __a , __a = self._main_retrieve(__lowercase , __lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowercase ) # distributed training __a = dist.get_world_size(group=self.process_group ) # gather logic __a = None if self._is_main(): __a = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowercase )] dist.gather(torch.tensor(__lowercase ) , dst=0 , gather_list=__lowercase , group=self.process_group ) # scatter logic __a = question_hidden_states.shape[0] __a = [] __a = [] if self._is_main(): assert len(__lowercase ) == world_size __a , __a = self._main_retrieve(torch.cat(__lowercase ).numpy() , __lowercase ) __a , __a = torch.tensor(__lowercase ), torch.tensor(__lowercase ) __a = self._chunk_tensor(__lowercase , __lowercase ) __a = self._chunk_tensor(__lowercase , __lowercase ) __a = self._scattered(__lowercase , [n_queries, n_docs] , target_type=torch.intaa ) __a = self._scattered(__lowercase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowercase )
225
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase_ ( unittest.TestCase): def __init__( self , a , a=7 , a=3 , a=1_8 , a=3_0 , a=4_0_0 , a=True , a=None , a=True , ) -> Optional[Any]: lowercase__ : str = size if size is not None else {'height': 1_8, 'width': 1_8} lowercase__ : int = parent lowercase__ : List[Any] = batch_size lowercase__ : Optional[int] = num_channels lowercase__ : Union[str, Any] = image_size lowercase__ : List[Any] = min_resolution lowercase__ : Any = max_resolution lowercase__ : List[Any] = do_resize lowercase__ : List[str] = size lowercase__ : Union[str, Any] = apply_ocr def _UpperCAmelCase ( self ) -> Any: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCAmelCase_ ( _a , unittest.TestCase): lowerCamelCase__ : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCAmelCase ( self ) -> List[str]: lowercase__ : Dict = LayoutLMvaImageProcessingTester(self ) @property def _UpperCAmelCase ( self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self ) -> int: lowercase__ : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'do_resize' ) ) self.assertTrue(hasattr(a , 'size' ) ) self.assertTrue(hasattr(a , 'apply_ocr' ) ) def _UpperCAmelCase ( self ) -> Any: lowercase__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) lowercase__ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def _UpperCAmelCase ( self ) -> Dict: pass def _UpperCAmelCase ( self ) -> Union[str, Any]: # Initialize image_processing lowercase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input lowercase__ : Dict = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , a ) self.assertIsInstance(encoding.boxes , a ) # Test batched lowercase__ : Optional[int] = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def _UpperCAmelCase ( self ) -> str: # Initialize image_processing lowercase__ : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input lowercase__ : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowercase__ : Optional[int] = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def _UpperCAmelCase ( self ) -> Dict: # Initialize image_processing lowercase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input lowercase__ : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowercase__ : List[str] = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def _UpperCAmelCase ( self ) -> List[str]: # with apply_OCR = True lowercase__ : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset lowercase__ : Optional[Any] = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowercase__ : List[Any] = Image.open(ds[0]['file'] ).convert('RGB' ) lowercase__ : Dict = image_processing(a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowercase__ : str = [['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 lowercase__ : Any = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a ) self.assertListEqual(encoding.boxes , a ) # with apply_OCR = False lowercase__ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a ) lowercase__ : Dict = image_processing(a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
645
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class UpperCAmelCase_ : def __init__( self , a , a=1_3 , a=3_2 , a=2 , a=3 , a=1_6 , a=[1, 2, 1] , a=[2, 2, 4] , a=2 , a=2.0 , a=True , a=0.0 , a=0.0 , a=0.1 , a="gelu" , a=False , a=True , a=0.02 , a=1e-5 , a=True , a=None , a=True , a=1_0 , a=8 , a=["stage1", "stage2", "stage3"] , a=[1, 2, 3] , ) -> int: lowercase__ : int = parent lowercase__ : Union[str, Any] = batch_size lowercase__ : Dict = image_size lowercase__ : str = patch_size lowercase__ : Optional[Any] = num_channels lowercase__ : List[str] = embed_dim lowercase__ : Any = depths lowercase__ : Dict = num_heads lowercase__ : List[str] = window_size lowercase__ : int = mlp_ratio lowercase__ : Tuple = qkv_bias lowercase__ : Union[str, Any] = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Tuple = drop_path_rate lowercase__ : List[str] = hidden_act lowercase__ : Optional[Any] = use_absolute_embeddings lowercase__ : Optional[Any] = patch_norm lowercase__ : Any = layer_norm_eps lowercase__ : List[Any] = initializer_range lowercase__ : List[str] = is_training lowercase__ : int = scope lowercase__ : Optional[int] = use_labels lowercase__ : List[Any] = type_sequence_label_size lowercase__ : List[str] = encoder_stride lowercase__ : Optional[Any] = out_features lowercase__ : Dict = out_indices def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Optional[Any] = None if self.use_labels: lowercase__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Tuple = self.get_config() return config, pixel_values, labels def _UpperCAmelCase ( self ) -> Union[str, Any]: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _UpperCAmelCase ( self , a , a , a ) -> Dict: lowercase__ : Tuple = MaskFormerSwinModel(config=a ) model.to(a ) model.eval() lowercase__ : str = model(a ) lowercase__ : str = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ : Dict = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _UpperCAmelCase ( self , a , a , a ) -> Optional[int]: lowercase__ : List[Any] = MaskFormerSwinBackbone(config=a ) model.to(a ) model.eval() lowercase__ : int = model(a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(a ): lowercase__ : Dict = ['stem'] lowercase__ : List[str] = MaskFormerSwinBackbone(config=a ) def _UpperCAmelCase ( self ) -> str: lowercase__ : int = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Tuple = config_and_inputs lowercase__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _a , _a , unittest.TestCase): lowerCamelCase__ : Optional[int] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowerCamelCase__ : List[str] = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} lowerCamelCase__ : str = False lowerCamelCase__ : Dict = False lowerCamelCase__ : Any = False lowerCamelCase__ : Dict = False lowerCamelCase__ : int = False def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = MaskFormerSwinModelTester(self ) lowercase__ : Tuple = ConfigTester(self , config_class=a , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def _UpperCAmelCase ( self ) -> Optional[int]: pass def _UpperCAmelCase ( self ) -> Tuple: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCAmelCase ( self ) -> str: return def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a ) @unittest.skip('Swin does not use inputs_embeds' ) def _UpperCAmelCase ( self ) -> Tuple: pass @unittest.skip('Swin does not support feedforward chunking' ) def _UpperCAmelCase ( self ) -> Tuple: pass def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[str] = model_class(a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def _UpperCAmelCase ( self ) -> str: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) lowercase__ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[Any] = [*signature.parameters.keys()] lowercase__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def _UpperCAmelCase ( self ) -> List[Any]: pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def _UpperCAmelCase ( self ) -> int: pass def _UpperCAmelCase ( self , a , a , a , a ) -> Tuple: lowercase__ : Dict = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : str = model(**self._prepare_for_class(a , a ) ) lowercase__ : List[Any] = outputs.hidden_states lowercase__ : str = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(a ) , a ) # Swin has a different seq_length lowercase__ : Dict = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = 3 lowercase__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Optional[int] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : int = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def _UpperCAmelCase ( self ) -> Optional[int]: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass def _UpperCAmelCase ( self ) -> Any: lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(a ): lowercase__ : Union[str, Any] = 0 return t def check_equivalence(a , a , a , a={} ): with torch.no_grad(): lowercase__ : Optional[Any] = model(**a , return_dict=a , **a ) lowercase__ : Optional[int] = model(**a , return_dict=a , **a ).to_tuple() def recursive_check(a , a ): if isinstance(a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a , a ): recursive_check(a , a ) elif isinstance(a , a ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(a , a ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(a ) , set_nan_tensor_to_zero(a ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" f""" {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}. Dict has""" f""" `nan`: {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}.""" ) , ) recursive_check(a , a ) for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) model.to(a ) model.eval() lowercase__ : Tuple = self._prepare_for_class(a , a ) lowercase__ : Optional[Any] = self._prepare_for_class(a , a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : List[Any] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a ) lowercase__ : int = self._prepare_for_class(a , a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) lowercase__ : Dict = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : Optional[int] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) @require_torch class UpperCAmelCase_ ( unittest.TestCase , _a): lowerCamelCase__ : Dict = (MaskFormerSwinBackbone,) if is_torch_available() else () lowerCamelCase__ : Optional[int] = MaskFormerSwinConfig def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Optional[int] = MaskFormerSwinModelTester(self ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: lowercase__ : Optional[Any] = backbone_class(a ) backbone.to(a ) backbone.eval() lowercase__ : Union[str, Any] = backbone(**a ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , a ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowercase__ : List[str] = backbone(**a , output_hidden_states=a ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowercase__ , lowercase__ , lowercase__ : int = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowercase__ : List[Any] = backbone(**a , output_attentions=a ) self.assertIsNotNone(outputs.attentions )
645
1
'''simple docstring''' import unittest from transformers import DonutProcessor a : Union[str, Any] = '''naver-clova-ix/donut-base''' class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Optional[Any] ): """simple docstring""" __snake_case = DonutProcessor.from_pretrained(a_ ) def A ( self : Tuple ): """simple docstring""" __snake_case = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } __snake_case = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) __snake_case = self.processor.tokenajson(a_ ) self.assertDictEqual(a_ , a_ )
69
'''simple docstring''' import functools def _UpperCAmelCase ( __A : list[int] , __A : list[int] ): # Validation if not isinstance(__A , __A ) or not all(isinstance(__A , __A ) for day in days ): raise ValueError('''The parameter days should be a list of integers''' ) if len(__A ) != 3 or not all(isinstance(__A , __A ) for cost in costs ): raise ValueError('''The parameter costs should be a list of three integers''' ) if len(__A ) == 0: return 0 if min(__A ) <= 0: raise ValueError('''All days elements should be greater than 0''' ) if max(__A ) >= 3_66: raise ValueError('''All days elements should be less than 366''' ) a_ : List[Any] = set(__A ) @functools.cache def dynamic_programming(__A : int ) -> int: if index > 3_65: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
466
0
'''simple docstring''' def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case_ : Tuple = generate_pascal_triangle(__SCREAMING_SNAKE_CASE ) for row_idx in range(__SCREAMING_SNAKE_CASE ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx], end=" " ) else: print(triangle[row_idx][col_idx], end="" ) print() def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) snake_case_ : list[list[int]] = [] for current_row_idx in range(__SCREAMING_SNAKE_CASE ): snake_case_ : Dict = populate_current_row(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) triangle.append(__SCREAMING_SNAKE_CASE ) return triangle def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case_ : Dict = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 snake_case_ : Union[str, Any] = 1, 1 for current_col_idx in range(1, __SCREAMING_SNAKE_CASE ): calculate_current_element( __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) return current_row def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, ): """simple docstring""" snake_case_ : Dict = triangle[current_row_idx - 1][current_col_idx - 1] snake_case_ : Optional[Any] = triangle[current_row_idx - 1][current_col_idx] snake_case_ : List[Any] = above_to_left_elt + above_to_right_elt def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) snake_case_ : list[list[int]] = [[1]] for row_index in range(1, __SCREAMING_SNAKE_CASE ): snake_case_ : Any = [0] + result[-1] + [0] snake_case_ : Dict = row_index + 1 # Calculate the number of distinct elements in a row snake_case_ : Any = sum(divmod(__SCREAMING_SNAKE_CASE, 2 ) ) snake_case_ : Tuple = [ temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1 ) ] snake_case_ : Dict = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() snake_case_ : Optional[int] = row_first_half + row_second_half result.append(__SCREAMING_SNAKE_CASE ) return result def UpperCamelCase_ ( ): """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) -> None: snake_case_ : int = f'{func.__name__}({value})' snake_case_ : List[Any] = timeit(f'__main__.{call}', setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'{call:38} -- {timing:.4f} seconds' ) for value in range(1_5 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
706
'''simple docstring''' import doctest from collections import deque import numpy as np class UpperCAmelCase_ : def __init__( self): snake_case_ : List[Any] = [2, 1, 2, -1] snake_case_ : int = [1, 2, 3, 4] def snake_case__ ( self): snake_case_ : str = len(self.first_signal) snake_case_ : Any = len(self.second_signal) snake_case_ : List[Any] = max(lowercase_ , lowercase_) # create a zero matrix of max_length x max_length snake_case_ : Dict = [[0] * max_length for i in range(lowercase_)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(lowercase_): snake_case_ : List[str] = deque(self.second_signal) rotated_signal.rotate(lowercase_) for j, item in enumerate(lowercase_): matrix[i][j] += item # multiply the matrix with the first signal snake_case_ : Any = np.matmul(np.transpose(lowercase_) , np.transpose(self.first_signal)) # rounding-off to two decimal places return [round(lowercase_ , 2) for i in final_signal] if __name__ == "__main__": doctest.testmod()
92
0
def a__ (__lowercase :int ) -> str: _A : str = len(__lowercase ) _A : str = sum(__lowercase ) _A : List[Any] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): _A : Dict = True for i in range(1 , s + 1 ): _A : Any = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): _A : int = dp[i][j - 1] if arr[i - 1] <= j: _A : Union[str, Any] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: _A : Any = s - 2 * j break return diff
206
import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging _UpperCamelCase : Optional[Any] =logging.get_logger(__name__) def a__ () -> Any: # Get the sagemaker specific mp parameters from smp_options variable. _A : Any = os.getenv('''SM_HP_MP_PARAMETERS''' , '''{}''' ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. _A : Dict = json.loads(__lowercase ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. _A : Optional[int] = os.getenv('''SM_FRAMEWORK_PARAMS''' , '''{}''' ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". _A : Any = json.loads(__lowercase ) if not mpi_options.get('''sagemaker_mpi_enabled''' , __lowercase ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec('''smdistributed''' ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCAmelCase__ ( __snake_case ): __snake_case : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def A__ ( self ): super().__post_init__() warnings.warn( '''`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use ''' '''`TrainingArguments` instead.''' ,A__ ,) @cached_property def A__ ( self ): logger.info('''PyTorch: setting up devices''' ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( '''torch.distributed process group is initialized, but local_rank == -1. ''' '''In order to use Torch DDP, launch your script with `python -m torch.distributed.launch''' ) if self.no_cuda: _A : Union[str, Any] = torch.device('''cpu''' ) _A : List[str] = 0 elif is_sagemaker_model_parallel_available(): _A : Dict = smp.local_rank() _A : Union[str, Any] = torch.device('''cuda''' ,A__ ) _A : Tuple = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend='''smddp''' ,timeout=self.ddp_timeout_delta ) _A : int = int(os.getenv('''SMDATAPARALLEL_LOCAL_RANK''' ) ) _A : int = torch.device('''cuda''' ,self.local_rank ) _A : Union[str, Any] = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 _A : Dict = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. _A : Union[str, Any] = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend='''nccl''' ,timeout=self.ddp_timeout_delta ) _A : Union[str, Any] = torch.device('''cuda''' ,self.local_rank ) _A : List[Any] = 1 if device.type == "cuda": torch.cuda.set_device(A__ ) return device @property def A__ ( self ): if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def A__ ( self ): return not is_sagemaker_model_parallel_available() @property def A__ ( self ): return False
206
1
import itertools import math def __lowerCamelCase (UpperCAmelCase__ : int ): 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 (): SCREAMING_SNAKE_CASE = 2 while True: if is_prime(UpperCAmelCase__ ): yield num num += 1 def __lowerCamelCase (UpperCAmelCase__ : int = 1_0_0_0_1 ): return next(itertools.islice(prime_generator() , nth - 1 , UpperCAmelCase__ ) ) if __name__ == "__main__": print(f"""{solution() = }""")
647
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) _lowerCamelCase : Optional[int] = logging.getLogger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' _lowerCamelCase : List[Any] = namedtuple( '''BertAbsConfig''', [ '''temp_dir''', '''large''', '''use_bert_emb''', '''finetune_bert''', '''encoder''', '''share_emb''', '''max_pos''', '''enc_layers''', '''enc_hidden_size''', '''enc_heads''', '''enc_ff_size''', '''enc_dropout''', '''dec_layers''', '''dec_hidden_size''', '''dec_heads''', '''dec_ff_size''', '''dec_dropout''', ], ) def __lowerCamelCase (UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] ): SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir="." , finetune_bert=UpperCAmelCase__ , large=UpperCAmelCase__ , share_emb=UpperCAmelCase__ , use_bert_emb=UpperCAmelCase__ , encoder="bert" , max_pos=5_1_2 , enc_layers=6 , enc_hidden_size=5_1_2 , enc_heads=8 , enc_ff_size=5_1_2 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_6_8 , dec_heads=8 , dec_ff_size=2_0_4_8 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE = torch.load(UpperCAmelCase__ , lambda UpperCAmelCase__ , UpperCAmelCase__ : storage ) SCREAMING_SNAKE_CASE = AbsSummarizer(UpperCAmelCase__ , torch.device("cpu" ) , UpperCAmelCase__ ) original.eval() SCREAMING_SNAKE_CASE = BertAbsSummarizer(UpperCAmelCase__ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs SCREAMING_SNAKE_CASE = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(UpperCAmelCase__ )) ) SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(UpperCAmelCase__ )) ) SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE = encoder_input_ids SCREAMING_SNAKE_CASE = decoder_input_ids SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE = original(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE = original.generator(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = new_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE = new_model.generator(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(UpperCAmelCase__ ) ) SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(UpperCAmelCase__ ) ) SCREAMING_SNAKE_CASE = torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": _lowerCamelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--bertabs_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''', ) _lowerCamelCase : Any = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
647
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class lowercase(unittest.TestCase ): __snake_case: Union[str, Any] = MODEL_FOR_CAUSAL_LM_MAPPING __snake_case: Union[str, Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowercase__ ( self ) -> Union[str, Any]: """simple docstring""" a__ = pipeline(task='text-generation' , model='sshleifer/tiny-ctrl' , framework='pt' ) # Using `do_sample=False` to force deterministic output a__ = text_generator('This is a test' , do_sample=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ { 'generated_text': ( 'This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.' ' oscope. FiliFili@@' ) } ] , ) a__ = text_generator(['This is a test', 'This is a second test'] ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [ { 'generated_text': ( 'This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.' ' oscope. FiliFili@@' ) } ], [ { 'generated_text': ( 'This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy' ' oscope. oscope. FiliFili@@' ) } ], ] , ) a__ = text_generator('This is a test' , do_sample=__SCREAMING_SNAKE_CASE , num_return_sequences=2 , return_tensors=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, ] , ) a__ = text_generator.model.config.eos_token_id a__ = '<pad>' a__ = text_generator( ['This is a test', 'This is a second test'] , do_sample=__SCREAMING_SNAKE_CASE , num_return_sequences=2 , batch_size=2 , return_tensors=__SCREAMING_SNAKE_CASE , ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [ {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_token_ids': ANY(__SCREAMING_SNAKE_CASE )}, ], ] , ) @require_tf def lowercase__ ( self ) -> Optional[int]: """simple docstring""" a__ = pipeline(task='text-generation' , model='sshleifer/tiny-ctrl' , framework='tf' ) # Using `do_sample=False` to force deterministic output a__ = text_generator('This is a test' , do_sample=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ { 'generated_text': ( 'This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵' ' please,' ) } ] , ) a__ = text_generator(['This is a test', 'This is a second test'] , do_sample=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [ { 'generated_text': ( 'This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵' ' please,' ) } ], [ { 'generated_text': ( 'This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes' ' Cannes 閲閲Cannes Cannes Cannes 攵 please,' ) } ], ] , ) def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" a__ = TextGenerationPipeline(model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) return text_generator, ["This is a test", "Another test"] def lowercase__ ( self ) -> int: """simple docstring""" a__ = 'Hello I believe in' a__ = pipeline('text-generation' , model='hf-internal-testing/tiny-random-gpt2' ) a__ = text_generator(__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [{'generated_text': 'Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'}] , ) a__ = text_generator(__SCREAMING_SNAKE_CASE , stop_sequence=' fe' ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': 'Hello I believe in fe'}] ) def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" a__ = text_generator.model a__ = text_generator.tokenizer a__ = text_generator('This is a test' ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}] ) self.assertTrue(outputs[0]['generated_text'].startswith('This is a test' ) ) a__ = text_generator('This is a test' , return_full_text=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}] ) self.assertNotIn('This is a test' , outputs[0]['generated_text'] ) a__ = pipeline(task='text-generation' , model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , return_full_text=__SCREAMING_SNAKE_CASE ) a__ = text_generator('This is a test' ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}] ) self.assertNotIn('This is a test' , outputs[0]['generated_text'] ) a__ = text_generator('This is a test' , return_full_text=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}] ) self.assertTrue(outputs[0]['generated_text'].startswith('This is a test' ) ) a__ = text_generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_text': ANY(__SCREAMING_SNAKE_CASE )}], [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_text': ANY(__SCREAMING_SNAKE_CASE )}], ] , ) if text_generator.tokenizer.pad_token is not None: a__ = text_generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_text': ANY(__SCREAMING_SNAKE_CASE )}], [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}, {'generated_text': ANY(__SCREAMING_SNAKE_CASE )}], ] , ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): a__ = text_generator('test' , return_full_text=__SCREAMING_SNAKE_CASE , return_text=__SCREAMING_SNAKE_CASE ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): a__ = text_generator('test' , return_full_text=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): a__ = text_generator('test' , return_text=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): a__ = text_generator('' ) self.assertEqual(__SCREAMING_SNAKE_CASE , [{'generated_text': ANY(__SCREAMING_SNAKE_CASE )}] ) else: with self.assertRaises((ValueError, AssertionError) ): a__ = text_generator('' ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. a__ = ['RwkvForCausalLM', 'XGLMForCausalLM', 'GPTNeoXForCausalLM'] if ( tokenizer.model_max_length < 1_0_0_0_0 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator('This is a test' * 5_0_0 , max_new_tokens=2_0 ) a__ = text_generator('This is a test' * 5_0_0 , handle_long_generation='hole' , max_new_tokens=2_0 ) # Hole strategy cannot work with self.assertRaises(__SCREAMING_SNAKE_CASE ): text_generator( 'This is a test' * 5_0_0 , handle_long_generation='hole' , max_new_tokens=tokenizer.model_max_length + 1_0 , ) @require_torch @require_accelerate @require_torch_gpu def lowercase__ ( self ) -> List[Any]: """simple docstring""" import torch # Classic `model_kwargs` a__ = pipeline( model='hf-internal-testing/tiny-random-bloom' , model_kwargs={'device_map': 'auto', 'torch_dtype': torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) a__ = pipe('This is a test' ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) a__ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) a__ = pipe('This is a test' ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 a__ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) a__ = pipe('This is a test' ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) @require_torch @require_torch_gpu def lowercase__ ( self ) -> Any: """simple docstring""" import torch a__ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device=0 , torch_dtype=torch.floataa ) pipe('This is a test' ) @require_torch @require_accelerate @require_torch_gpu def lowercase__ ( self ) -> Dict: """simple docstring""" import torch a__ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' , torch_dtype=torch.floataa ) pipe('This is a test' , do_sample=__SCREAMING_SNAKE_CASE , top_p=0.5 ) def lowercase__ ( self ) -> int: """simple docstring""" a__ = 'Hello world' a__ = pipeline('text-generation' , model='hf-internal-testing/tiny-random-gpt2' ) if text_generator.model.framework == "tf": a__ = logging.get_logger('transformers.generation.tf_utils' ) else: a__ = logging.get_logger('transformers.generation.utils' ) a__ = 'Both `max_new_tokens`' # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: a__ = text_generator(__SCREAMING_SNAKE_CASE , max_length=1_0 , max_new_tokens=1 ) self.assertIn(__SCREAMING_SNAKE_CASE , cl.out ) # The user only sets one -> no warning with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: a__ = text_generator(__SCREAMING_SNAKE_CASE , max_new_tokens=1 ) self.assertNotIn(__SCREAMING_SNAKE_CASE , cl.out ) with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: a__ = text_generator(__SCREAMING_SNAKE_CASE , max_length=1_0 ) self.assertNotIn(__SCREAMING_SNAKE_CASE , cl.out )
273
"""simple docstring""" from collections import deque class lowercase: def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" a__ = process_name # process name a__ = arrival_time # arrival time of the process # completion time of finished process or last interrupted time a__ = arrival_time a__ = burst_time # remaining burst time a__ = 0 # total time of the process wait in ready queue a__ = 0 # time from arrival time to completion time class lowercase: def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" a__ = number_of_queues # time slice of queues that round robin algorithm applied a__ = time_slices # unfinished process is in this ready_queue a__ = queue # current time a__ = current_time # finished process is in this sequence queue a__ = deque() def lowercase__ ( self ) -> list[str]: """simple docstring""" a__ = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" a__ = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" a__ = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" a__ = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): completion_times.append(queue[i].stop_time ) return completion_times def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" return [q.burst_time for q in queue] def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> deque[Process]: """simple docstring""" a__ = deque() # sequence deque of finished process while len(__SCREAMING_SNAKE_CASE ) != 0: a__ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 a__ = 0 # set the process's turnaround time because it is finished a__ = self.current_time - cp.arrival_time # set the completion time a__ = self.current_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> tuple[deque[Process], deque[Process]]: """simple docstring""" a__ = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(__SCREAMING_SNAKE_CASE ) ): a__ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time a__ = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(__SCREAMING_SNAKE_CASE ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished a__ = 0 # set the finish time a__ = self.current_time # update the process' turnaround time because it is finished a__ = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def lowercase__ ( self ) -> deque[Process]: """simple docstring""" for i in range(self.number_of_queues - 1 ): a__ , a__ = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest a : List[str] = Process('P1', 0, 53) a : Optional[int] = Process('P2', 0, 17) a : Union[str, Any] = Process('P3', 0, 68) a : Optional[int] = Process('P4', 0, 24) a : Optional[int] = 3 a : Optional[Any] = [17, 25] a : Union[str, Any] = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) a : Union[str, Any] = Process('P1', 0, 53) a : Optional[int] = Process('P2', 0, 17) a : Optional[Any] = Process('P3', 0, 68) a : str = Process('P4', 0, 24) a : Optional[Any] = 3 a : Tuple = [17, 25] a : int = deque([Pa, Pa, Pa, Pa]) a : Tuple = MLFQ(number_of_queues, time_slices, queue, 0) a : Optional[int] = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( F'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( F'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( F'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
273
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE = { "configuration_squeezebert": [ "SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "SqueezeBertConfig", "SqueezeBertOnnxConfig", ], "tokenization_squeezebert": ["SqueezeBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = ["SqueezeBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ "SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "SqueezeBertForMaskedLM", "SqueezeBertForMultipleChoice", "SqueezeBertForQuestionAnswering", "SqueezeBertForSequenceClassification", "SqueezeBertForTokenClassification", "SqueezeBertModel", "SqueezeBertModule", "SqueezeBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
517
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : List[str] )-> Optional[int]: snake_case = inspect.getfile(accelerate.test_utils ) snake_case = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) snake_case = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def lowerCAmelCase ( self : int )-> List[str]: snake_case = f''' {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} '''.split() snake_case = [sys.executable] + distributed_args execute_subprocess_async(__snake_case , env=os.environ.copy() )
517
1
class lowerCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self , __lowercase , __lowercase , __lowercase) -> Tuple: __UpperCamelCase :str = row __UpperCamelCase :Optional[int] = col __UpperCamelCase :Any = graph def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> Optional[Any]: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> int: # Checking all 8 elements surrounding nth element __UpperCamelCase :Optional[int] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order __UpperCamelCase :Dict = [-1, 0, 1, -1, 1, -1, 0, 1] __UpperCamelCase :Union[str, Any] = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , _snake_case): self.diffs(i + row_nbr[k] , j + col_nbr[k] , _snake_case) def UpperCamelCase__ ( self) -> Optional[int]: # And finally, count all islands. __UpperCamelCase :Optional[int] = [[False for j in range(self.COL)] for i in range(self.ROW)] __UpperCamelCase :Tuple = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(_snake_case , _snake_case , _snake_case) count += 1 return count
167
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = "\\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" snake_case = "\\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" snake_case = "\\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 __A ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): 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 , _snake_case , _snake_case , _snake_case = 1 , _snake_case = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_snake_case , hypotheses=_snake_case , min_len=_snake_case , max_len=_snake_case ) }
424
0
'''simple docstring''' from __future__ import annotations def A__ ( __lowerCAmelCase : int = 4 ): lowerCamelCase__ = abs(__lowerCAmelCase ) or 4 return [[1 + x + y * row_size for x in range(__lowerCAmelCase )] for y in range(__lowerCAmelCase )] def A__ ( __lowerCAmelCase : list[list[int]] ): return reverse_row(transpose(__lowerCAmelCase ) ) # OR.. transpose(reverse_column(matrix)) def A__ ( __lowerCAmelCase : list[list[int]] ): return reverse_row(reverse_column(__lowerCAmelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def A__ ( __lowerCAmelCase : list[list[int]] ): return reverse_column(transpose(__lowerCAmelCase ) ) # OR.. transpose(reverse_row(matrix)) def A__ ( __lowerCAmelCase : list[list[int]] ): lowerCamelCase__ = [list(__lowerCAmelCase ) for x in zip(*__lowerCAmelCase )] return matrix def A__ ( __lowerCAmelCase : list[list[int]] ): lowerCamelCase__ = matrix[::-1] return matrix def A__ ( __lowerCAmelCase : list[list[int]] ): lowerCamelCase__ = [x[::-1] for x in matrix] return matrix def A__ ( __lowerCAmelCase : list[list[int]] ): for i in matrix: print(*__lowerCAmelCase ) if __name__ == "__main__": UpperCamelCase : Any = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 90 counterclockwise:\n') print_matrix(rotate_aa(matrix)) UpperCamelCase : int = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 180:\n') print_matrix(rotate_aaa(matrix)) UpperCamelCase : Dict = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 270 counterclockwise:\n') print_matrix(rotate_aaa(matrix))
706
'''simple docstring''' from math import factorial UpperCamelCase : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def A__ ( __lowerCAmelCase : int ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError("""Parameter number must be int""" ) if number < 0: raise ValueError("""Parameter number must be greater than or equal to 0""" ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(__lowerCAmelCase ) ) def A__ ( __lowerCAmelCase : int = 60 , __lowerCAmelCase : int = 100_0000 ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError("""Parameters chain_length and number_limit must be int""" ) if chain_length <= 0 or number_limit <= 0: raise ValueError( """Parameters chain_length and number_limit must be greater than 0""" ) # the counter for the chains with the exact desired length lowerCamelCase__ = 0 # the cached sizes of the previous chains lowerCamelCase__ = {} for start_chain_element in range(1 , __lowerCAmelCase ): # The temporary set will contain the elements of the chain lowerCamelCase__ = set() lowerCamelCase__ = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. lowerCamelCase__ = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(__lowerCAmelCase ) chain_set_length += 1 lowerCamelCase__ = digit_factorial_sum(__lowerCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] lowerCamelCase__ = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'{solution()}')
9
0
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE__ ( ) -> Union[str, Any]: lowercase__: List[str] = HfArgumentParser(_lowerCamelCase ) lowercase__: Tuple = parser.parse_args_into_dataclasses()[0] lowercase__: Optional[int] = TensorFlowBenchmark(args=_lowerCamelCase ) try: lowercase__: Optional[Any] = parser.parse_args_into_dataclasses()[0] except ValueError as e: lowercase__: Tuple = "Arg --no_{0} is no longer used, please use --no-{0} instead." lowercase__: Any = " ".join(str(_lowerCamelCase ).split(''' ''' )[:-1] ) lowercase__: Dict = "" lowercase__: Optional[Any] = eval(str(_lowerCamelCase ).split(''' ''' )[-1] ) lowercase__: Optional[int] = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(_lowerCamelCase ) if len(_lowerCamelCase ) > 0: lowercase__: Union[str, Any] = full_error_msg + begin_error_msg + str(_lowerCamelCase ) raise ValueError(_lowerCamelCase ) benchmark.run() if __name__ == "__main__": main()
586
"""simple docstring""" import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : List[Any] = "laion/clap-htsat-unfused" __lowerCamelCase : Tuple = tempfile.mkdtemp() def lowerCamelCase__ ( self : Tuple , **UpperCAmelCase : str ): return RobertaTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase ) def lowerCamelCase__ ( self : List[str] , **UpperCAmelCase : Optional[int] ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ): shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self : Any ): __lowerCamelCase : List[str] = self.get_tokenizer() __lowerCamelCase : Optional[Any] = self.get_feature_extractor() __lowerCamelCase : List[str] = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) def lowerCamelCase__ ( self : int ): __lowerCamelCase : Union[str, Any] = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase : Any = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __lowerCamelCase : Union[str, Any] = self.get_feature_extractor(do_normalize=UpperCAmelCase , padding_value=1.0 ) __lowerCamelCase : str = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) def lowerCamelCase__ ( self : str ): __lowerCamelCase : Tuple = self.get_feature_extractor() __lowerCamelCase : Optional[Any] = self.get_tokenizer() __lowerCamelCase : Dict = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) __lowerCamelCase : List[str] = floats_list((3, 1000) ) __lowerCamelCase : List[Any] = feature_extractor(UpperCAmelCase , return_tensors="np" ) __lowerCamelCase : List[Any] = processor(audios=UpperCAmelCase , 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 lowerCamelCase__ ( self : str ): __lowerCamelCase : Any = self.get_feature_extractor() __lowerCamelCase : Optional[int] = self.get_tokenizer() __lowerCamelCase : List[Any] = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) __lowerCamelCase : Any = "This is a test string" __lowerCamelCase : Dict = processor(text=UpperCAmelCase ) __lowerCamelCase : Dict = tokenizer(UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase__ ( self : Any ): __lowerCamelCase : str = self.get_feature_extractor() __lowerCamelCase : Any = self.get_tokenizer() __lowerCamelCase : List[Any] = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) __lowerCamelCase : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase : List[str] = processor.batch_decode(UpperCAmelCase ) __lowerCamelCase : str = tokenizer.batch_decode(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def lowerCamelCase__ ( self : List[str] ): __lowerCamelCase : Tuple = self.get_feature_extractor() __lowerCamelCase : int = self.get_tokenizer() __lowerCamelCase : Tuple = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
646
0
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=30 , snake_case__=2 , snake_case__=3 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=2 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , snake_case__=2 , ): """simple docstring""" lowerCAmelCase : List[str] = parent lowerCAmelCase : int = batch_size lowerCAmelCase : Optional[int] = image_size lowerCAmelCase : Optional[Any] = patch_size lowerCAmelCase : Optional[int] = num_channels lowerCAmelCase : Dict = is_training lowerCAmelCase : List[Any] = use_labels lowerCAmelCase : List[Any] = hidden_size lowerCAmelCase : Optional[int] = num_hidden_layers lowerCAmelCase : int = num_attention_heads lowerCAmelCase : Tuple = intermediate_size lowerCAmelCase : Union[str, Any] = hidden_act lowerCAmelCase : Any = hidden_dropout_prob lowerCAmelCase : Dict = attention_probs_dropout_prob lowerCAmelCase : Tuple = type_sequence_label_size lowerCAmelCase : Dict = initializer_range lowerCAmelCase : Optional[int] = scope lowerCAmelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) lowerCAmelCase : Tuple = (image_size // patch_size) ** 2 lowerCAmelCase : Union[str, Any] = num_patches + 2 def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase : str = None if self.use_labels: lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase : List[Any] = self.get_config() return config, pixel_values, labels def lowercase__ ( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Tuple = TFDeiTModel(config=snake_case__ ) lowerCAmelCase : Union[str, Any] = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : List[Any] = TFDeiTForMaskedImageModeling(config=snake_case__ ) lowerCAmelCase : str = model(snake_case__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowerCAmelCase : str = 1 lowerCAmelCase : str = TFDeiTForMaskedImageModeling(snake_case__ ) lowerCAmelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase : Any = model(snake_case__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Optional[int] = self.type_sequence_label_size lowerCAmelCase : Dict = TFDeiTForImageClassification(snake_case__ ) lowerCAmelCase : Tuple = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase : List[str] = 1 lowerCAmelCase : Union[str, Any] = TFDeiTForImageClassification(snake_case__ ) lowerCAmelCase : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase : List[Any] = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase : Any = config_and_inputs lowerCAmelCase : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( __A , __A , unittest.TestCase ): """simple docstring""" a : str =( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) a : Union[str, Any] =( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) a : Union[str, Any] =False a : List[str] =False a : Union[str, Any] =False a : Union[str, Any] =False def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Dict = TFDeiTModelTester(self ) lowerCAmelCase : Optional[Any] = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def lowercase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : Union[str, Any] = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) lowerCAmelCase : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Dense ) ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : List[Any] = model_class(snake_case__ ) lowerCAmelCase : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase : List[Any] = [*signature.parameters.keys()] lowerCAmelCase : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__=False ): """simple docstring""" lowerCAmelCase : List[str] = super()._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowercase__ ( self ): """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase : Optional[int] = TFDeiTModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def a__ ( ): '''simple docstring''' lowerCAmelCase : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowercase__ ( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Dict = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) lowerCAmelCase : Union[str, Any] = self.default_image_processor lowerCAmelCase : List[Any] = prepare_img() lowerCAmelCase : Any = image_processor(images=snake_case__ , return_tensors="tf" ) # forward pass lowerCAmelCase : Optional[Any] = model(**snake_case__ ) # verify the logits lowerCAmelCase : str = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , snake_case__ ) lowerCAmelCase : Tuple = tf.constant([-1.0266, 0.1912, -1.2861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4 ) )
704
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : int = 1_0_0_0 ): '''simple docstring''' return sum(e for e in range(3 , SCREAMING_SNAKE_CASE ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F"{solution() = }")
681
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "caidas/swin2sr-classicalsr-x2-64": ( "https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json" ), } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = 'swin2sr' __UpperCAmelCase : List[Any] = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , _a=64 , _a=1 , _a=3 , _a=180 , _a=[6, 6, 6, 6, 6, 6] , _a=[6, 6, 6, 6, 6, 6] , _a=8 , _a=2.0 , _a=True , _a=0.0 , _a=0.0 , _a=0.1 , _a="gelu" , _a=False , _a=0.02 , _a=1E-5 , _a=2 , _a=1.0 , _a="1conv" , _a="pixelshuffle" , **_a , ): super().__init__(**_a ) __a = image_size __a = patch_size __a = num_channels __a = embed_dim __a = depths __a = len(_a ) __a = num_heads __a = window_size __a = mlp_ratio __a = qkv_bias __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = drop_path_rate __a = hidden_act __a = use_absolute_embeddings __a = layer_norm_eps __a = initializer_range __a = upscale __a = img_range __a = resi_connection __a = upsampler
695
"""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_ = 1_6 lowercase_ = 3_2 def lowercase ( lowerCAmelCase__ : Accelerator , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : str = "bert-base-cased" ) -> Optional[int]: __a = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) __a = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(lowerCAmelCase__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __a = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=lowerCAmelCase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(lowerCAmelCase__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(lowerCAmelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __a = DataLoader( tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) __a = DataLoader( tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]: # Initialize accelerator __a = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config['''lr'''] __a = int(config['''num_epochs'''] ) __a = int(config['''seed'''] ) __a = int(config['''batch_size'''] ) __a = args.model_name_or_path set_seed(lowerCAmelCase__ ) __a , __a = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer __a = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: __a = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: __a = 1 __a = (len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: __a = DummyScheduler(lowerCAmelCase__ , total_num_steps=lowerCAmelCase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over __a = 0 # We also need to keep track of the stating epoch so files are named properly __a = 0 # Now we train the model __a = evaluate.load('''glue''' , '''mrpc''' ) __a = 0 __a = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): __a = model(**lowerCAmelCase__ ) __a = outputs.loss __a = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() __a = 0 for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a = model(**lowerCAmelCase__ ) __a = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __a , __a = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: __a = predictions[: len(eval_dataloader.dataset ) - samples_seen] __a = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) __a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ ) __a = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: __a = 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(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( ) -> List[str]: __a = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=lowerCAmelCase__ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=lowerCAmelCase__ , ) parser.add_argument( '''--output_dir''' , type=lowerCAmelCase__ , 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=lowerCAmelCase__ , default=lowerCAmelCase__ , 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=lowerCAmelCase__ , default=3 , help='''Number of train epochs.''' , ) __a = parser.parse_args() __a = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
695
1
import os import unicodedata 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 A : str = logging.get_logger(__name__) A : Tuple = {"vocab_file": "spiece.model"} A : Union[str, Any] = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } A : Optional[Any] = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } A : List[Any] = "▁" class _lowercase ( lowercase__): """simple docstring""" A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Union[str, Any]="[CLS]" , __lowerCamelCase : List[str]="[SEP]" , __lowerCamelCase : Optional[int]="<unk>" , __lowerCamelCase : Optional[Any]="[SEP]" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : Optional[Any]="[CLS]" , __lowerCamelCase : List[str]="[MASK]" , __lowerCamelCase : Optional[Dict[str, Any]] = None , **__lowerCamelCase : Optional[int] , ): '''simple docstring''' lowerCamelCase__ : int = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) lowerCamelCase__ : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) lowerCamelCase__ : Union[str, Any] = do_lower_case lowerCamelCase__ : Optional[Any] = remove_space lowerCamelCase__ : int = keep_accents lowerCamelCase__ : Dict = vocab_file lowerCamelCase__ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def lowerCAmelCase ( self : int ): '''simple docstring''' return len(self.sp_model ) def lowerCAmelCase ( self : str ): '''simple docstring''' lowerCamelCase__ : Dict = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): '''simple docstring''' lowerCamelCase__ : Optional[Any] = self.__dict__.copy() lowerCamelCase__ : Optional[int] = None return state def __setstate__( self : Tuple , __lowerCamelCase : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Any = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase__ : Dict = {} lowerCamelCase__ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : List[Any] , __lowerCamelCase : Tuple ): '''simple docstring''' if self.remove_space: lowerCamelCase__ : List[Any] = " ".join(inputs.strip().split() ) else: lowerCamelCase__ : str = inputs lowerCamelCase__ : List[str] = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase__ : Tuple = unicodedata.normalize("NFKD" , __lowerCamelCase ) lowerCamelCase__ : str = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: lowerCamelCase__ : Any = outputs.lower() return outputs def lowerCAmelCase ( self : Union[str, Any] , __lowerCamelCase : str ): '''simple docstring''' lowerCamelCase__ : List[Any] = self.preprocess_text(__lowerCamelCase ) lowerCamelCase__ : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) lowerCamelCase__ : Tuple = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase__ : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase__ : List[Any] = cur_pieces[1:] else: lowerCamelCase__ : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def lowerCAmelCase ( self : List[str] , __lowerCamelCase : List[Any] ): '''simple docstring''' return self.sp_model.PieceToId(__lowerCamelCase ) def lowerCAmelCase ( self : int , __lowerCamelCase : int ): '''simple docstring''' return self.sp_model.IdToPiece(__lowerCamelCase ) def lowerCAmelCase ( self : Tuple , __lowerCamelCase : List[str] ): '''simple docstring''' lowerCamelCase__ : Optional[int] = [] lowerCamelCase__ : Dict = "" lowerCamelCase__ : int = 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 lowerCamelCase__ : Dict = True lowerCamelCase__ : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) lowerCamelCase__ : Optional[Any] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def lowerCAmelCase ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowerCamelCase__ : Tuple = [self.sep_token_id] lowerCamelCase__ : List[str] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Union[str, Any] , __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 not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def lowerCAmelCase ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowerCamelCase__ : int = [self.sep_token_id] lowerCamelCase__ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : List[str] , __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 lowerCamelCase__ : str = 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: lowerCamelCase__ : Tuple = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
5
from __future__ import annotations def lowercase_ ( _A : str , _A : list[str] | None = None , _A : dict[str, float] | None = None , _A : bool = False , ): """simple docstring""" lowerCamelCase__ : Tuple = cipher_alphabet or [chr(_A ) for i in range(97 , 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) lowerCamelCase__ : Dict = { "a": 0.08_497, "b": 0.01_492, "c": 0.02_202, "d": 0.04_253, "e": 0.11_162, "f": 0.02_228, "g": 0.02_015, "h": 0.06_094, "i": 0.07_546, "j": 0.00_153, "k": 0.01_292, "l": 0.04_025, "m": 0.02_406, "n": 0.06_749, "o": 0.07_507, "p": 0.01_929, "q": 0.00_095, "r": 0.07_587, "s": 0.06_327, "t": 0.09_356, "u": 0.02_758, "v": 0.00_978, "w": 0.02_560, "x": 0.00_150, "y": 0.01_994, "z": 0.00_077, } else: # Custom frequencies dictionary lowerCamelCase__ : Optional[int] = frequencies_dict if not case_sensitive: lowerCamelCase__ : str = ciphertext.lower() # Chi squared statistic values lowerCamelCase__ : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(_A ) ): lowerCamelCase__ : Optional[Any] = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet lowerCamelCase__ : Dict = (alphabet_letters.index(letter.lower() ) - shift) % len( _A ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter lowerCamelCase__ : str = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: lowerCamelCase__ : List[str] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message lowerCamelCase__ : List[str] = decrypted_with_shift.lower().count(_A ) # Get the excepcted amount of times the letter should appear based # on letter frequencies lowerCamelCase__ : List[Any] = frequencies[letter] * occurrences # Complete the chi squared statistic formula lowerCamelCase__ : str = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message lowerCamelCase__ : Any = decrypted_with_shift.count(_A ) # Get the excepcted amount of times the letter should appear based # on letter frequencies lowerCamelCase__ : str = frequencies[letter] * occurrences # Complete the chi squared statistic formula lowerCamelCase__ : int = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary lowerCamelCase__ : Optional[int] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(_A : int ) -> tuple[float, str]: return chi_squared_statistic_values[key] lowerCamelCase__ : int = min( _A , key=_A , ) # Get all the data from the most likely cipher (key, decoded message) ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : int = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
5
1
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration UpperCAmelCase__ = "facebook/wmt19-en-de" UpperCAmelCase__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model UpperCAmelCase__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) UpperCAmelCase__ = FSMTForConditionalGeneration(config) print(f"""num of params {tiny_model.num_parameters()}""") # Test UpperCAmelCase__ = tokenizer(["Making tiny model"], return_tensors="pt") UpperCAmelCase__ = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save UpperCAmelCase__ = "tiny-wmt19-en-de" tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f"""Generated {mname_tiny}""") # Upload # transformers-cli upload tiny-wmt19-en-de
117
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def _a ( a :Optional[Any] ) -> List[Any]: if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: a = k.replace(a , a ) if k.startswith('''encoder''' ): a = k.replace('''.attn''' , '''.self_attn''' ) a = k.replace('''norm1''' , '''self_attn_layer_norm''' ) a = k.replace('''norm2''' , '''final_layer_norm''' ) elif k.startswith('''decoder''' ): a = k.replace('''norm1''' , '''self_attn_layer_norm''' ) a = k.replace('''norm2''' , '''encoder_attn_layer_norm''' ) a = k.replace('''norm3''' , '''final_layer_norm''' ) return k def _a ( a :Dict ) -> Tuple: a = [ '''model.encoder.layernorm_embedding.weight''', '''model.encoder.layernorm_embedding.bias''', '''model.decoder.layernorm_embedding.weight''', '''model.decoder.layernorm_embedding.bias''', ] for k in keys: a = sd.pop(a ) a = k.replace('''layernorm_embedding''' , '''layer_norm''' ) assert new_k not in sd a = v UpperCAmelCase__ = ["START"] @torch.no_grad() def _a ( a :Dict , a :str , a :int ) -> int: a = torch.load(a , map_location='''cpu''' ) a = model['''model'''] a = BlenderbotConfig.from_json_file(a ) a = BlenderbotForConditionalGeneration(a ) a = m.model.state_dict().keys() a = [] a = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue a = rename_state_dict_key(a ) if new_k not in valid_keys: failures.append([k, new_k] ) else: a = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(a ) m.model.load_state_dict(a , strict=a ) m.half() m.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) UpperCAmelCase__ = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
117
1
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) UpperCamelCase_ = 'hf-internal-testing/tiny-random-bert' UpperCamelCase_ = os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert') UpperCamelCase_ = '9b8c223d42b2188cb49d29af482996f9d0f3e5a6' class snake_case_ ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ =cached_file(A_, A_ ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(A_ ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(A_, A_ ) ) ) with open(os.path.join(A_, "refs", "main" ) ) as f: UpperCAmelCase__ =f.read() self.assertEqual(A_, os.path.join(A_, "snapshots", A_, A_ ) ) self.assertTrue(os.path.isfile(A_ ) ) # File is cached at the same place the second time. UpperCAmelCase__ =cached_file(A_, A_ ) self.assertEqual(A_, A_ ) # Using a specific revision to test the full commit hash. UpperCAmelCase__ =cached_file(A_, A_, revision="9b8c223" ) self.assertEqual(A_, os.path.join(A_, "snapshots", A_, A_ ) ) def __UpperCAmelCase ( self ) -> Tuple: with self.assertRaisesRegex(A_, "is not a valid model identifier" ): UpperCAmelCase__ =cached_file("tiny-random-bert", A_ ) with self.assertRaisesRegex(A_, "is not a valid git identifier" ): UpperCAmelCase__ =cached_file(A_, A_, revision="aaaa" ) with self.assertRaisesRegex(A_, "does not appear to have a file named" ): UpperCAmelCase__ =cached_file(A_, "conf" ) def __UpperCAmelCase ( self ) -> Optional[Any]: with self.assertRaisesRegex(A_, "does not appear to have a file named" ): UpperCAmelCase__ =cached_file(A_, "conf" ) with open(os.path.join(A_, "refs", "main" ) ) as f: UpperCAmelCase__ =f.read() self.assertTrue(os.path.isfile(os.path.join(A_, ".no_exist", A_, "conf" ) ) ) UpperCAmelCase__ =cached_file(A_, "conf", _raise_exceptions_for_missing_entries=A_ ) self.assertIsNone(A_ ) UpperCAmelCase__ =cached_file(A_, "conf", local_files_only=A_, _raise_exceptions_for_missing_entries=A_ ) self.assertIsNone(A_ ) UpperCAmelCase__ =mock.Mock() UpperCAmelCase__ =500 UpperCAmelCase__ ={} UpperCAmelCase__ =HTTPError UpperCAmelCase__ ={} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request", return_value=A_ ) as mock_head: UpperCAmelCase__ =cached_file(A_, "conf", _raise_exceptions_for_connection_errors=A_ ) self.assertIsNone(A_ ) # This check we did call the fake head request mock_head.assert_called() def __UpperCAmelCase ( self ) -> List[str]: self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only", A_ ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", A_ ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", A_ ) ) def __UpperCAmelCase ( self ) -> Optional[Any]: # `get_file_from_repo` returns None if the file does not exist self.assertIsNone(get_file_from_repo("bert-base-cased", "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(A_, "is not a valid model identifier" ): get_file_from_repo("bert-base-case", A_ ) # The function raises if the revision does not exist. with self.assertRaisesRegex(A_, "is not a valid git identifier" ): get_file_from_repo("bert-base-cased", A_, revision="ahaha" ) UpperCAmelCase__ =get_file_from_repo("bert-base-cased", A_ ) # The name is the cached name which is not very easy to test, so instead we load the content. UpperCAmelCase__ =json.loads(open(A_, "r" ).read() ) self.assertEqual(config["hidden_size"], 768 ) def __UpperCAmelCase ( self ) -> Optional[int]: with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ =Path(A_ ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(A_, "a.txt" ), str(A_ ) ) self.assertIsNone(get_file_from_repo(A_, "b.txt" ) )
510
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case_ ( a ): '''simple docstring''' __UpperCamelCase = ['image_processor', 'tokenizer'] __UpperCamelCase = 'BridgeTowerImageProcessor' __UpperCamelCase = ('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self, A_, A_ ) -> Dict: super().__init__(A_, A_ ) def __call__( self, A_, A_ = None, A_ = True, A_ = False, A_ = None, A_ = None, A_ = 0, A_ = None, A_ = None, A_ = None, A_ = False, A_ = False, A_ = False, A_ = False, A_ = True, A_ = None, **A_, ) -> BatchEncoding: UpperCAmelCase__ =self.tokenizer( text=A_, add_special_tokens=A_, padding=A_, truncation=A_, max_length=A_, stride=A_, pad_to_multiple_of=A_, return_token_type_ids=A_, return_attention_mask=A_, return_overflowing_tokens=A_, return_special_tokens_mask=A_, return_offsets_mapping=A_, return_length=A_, verbose=A_, return_tensors=A_, **A_, ) # add pixel_values + pixel_mask UpperCAmelCase__ =self.image_processor( A_, return_tensors=A_, do_normalize=A_, do_center_crop=A_, **A_ ) encoding.update(A_ ) return encoding def __UpperCAmelCase ( self, *A_, **A_ ) -> Any: return self.tokenizer.batch_decode(*A_, **A_ ) def __UpperCAmelCase ( self, *A_, **A_ ) -> Tuple: return self.tokenizer.decode(*A_, **A_ ) @property def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase__ =self.tokenizer.model_input_names UpperCAmelCase__ =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
510
1
from collections.abc import Callable def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = a _SCREAMING_SNAKE_CASE : Union[str, Any] = b if function(__lowerCamelCase ) == 0: # one of the a or b is a root for the function return a elif function(__lowerCamelCase ) == 0: return b elif ( function(__lowerCamelCase ) * function(__lowerCamelCase ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval." ) else: _SCREAMING_SNAKE_CASE : Dict = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(__lowerCamelCase ) == 0: return mid elif function(__lowerCamelCase ) * function(__lowerCamelCase ) < 0: _SCREAMING_SNAKE_CASE : List[Any] = mid else: _SCREAMING_SNAKE_CASE : Optional[int] = mid _SCREAMING_SNAKE_CASE : List[Any] = start + (end - start) / 2.0 return mid def lowerCamelCase__ (__lowerCamelCase ): return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
249
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) A__ : Any ={ '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] =['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any] =[ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys A__ : Tuple =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
207
0
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets UpperCamelCase__ : Dict = "\\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__ : List[Any] = "\\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__ : Union[str, Any] = "\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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return float((preds == labels).mean() ) def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ = simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = float(fa_score(y_true=_SCREAMING_SNAKE_CASE , y_pred=_SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.array(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = np.array(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = en_sentvecs.shape[0] # mean centering SCREAMING_SNAKE_CASE_ = en_sentvecs - np.mean(_SCREAMING_SNAKE_CASE , axis=0 ) SCREAMING_SNAKE_CASE_ = in_sentvecs - np.mean(_SCREAMING_SNAKE_CASE , axis=0 ) SCREAMING_SNAKE_CASE_ = cdist(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'cosine' ) SCREAMING_SNAKE_CASE_ = np.array(range(_SCREAMING_SNAKE_CASE ) ) SCREAMING_SNAKE_CASE_ = sim.argsort(axis=1 )[:, :10] SCREAMING_SNAKE_CASE_ = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __snake_case ( datasets.Metric ): def lowerCAmelCase__ ( self): 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 lowerCAmelCase__ ( self , _A , _A): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_A , _A)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_A , _A) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_A , _A)} 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"]')
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : List[Any] = torch.device("cpu") def _UpperCAmelCase ( ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] ) def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = val def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] for k in state_dict.keys(): SCREAMING_SNAKE_CASE_ = k if ".pwconv" in k: SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: SCREAMING_SNAKE_CASE_ = k_new.split('.' ) if ls[2].isdigit(): SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size SCREAMING_SNAKE_CASE_ = 1_000 SCREAMING_SNAKE_CASE_ = 'huggingface/label-files' SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4] SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6] SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5] SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6] SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) SCREAMING_SNAKE_CASE_ = checkpoint SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval() hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # prepare test inputs SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' ) SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # compare outputs from both models SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swiftformer_name", default="swiftformer_xs", choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"], type=str, help="Name of the SwiftFormer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="./converted_outputs/", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.") UpperCamelCase__ : Union[str, Any] = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
620
0
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class SCREAMING_SNAKE_CASE_ (_a ): '''simple docstring''' def __init__( self : Any , __a : Callable , __a : Optional[Features] = None , __a : str = None , __a : bool = False , __a : bool = False , __a : Optional[dict] = None , __a : Optional[int] = None , **__a : Optional[int] , ) ->Any: super().__init__( features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE , streaming=__SCREAMING_SNAKE_CASE , num_proc=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowerCamelCase_ : Optional[int] = Generator( cache_dir=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , gen_kwargs=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) def _lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: # Build iterable dataset if self.streaming: lowerCamelCase_ : Optional[int] = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: lowerCamelCase_ : Union[str, Any] = None lowerCamelCase_ : str = None lowerCamelCase_ : List[str] = None lowerCamelCase_ : Optional[int] = None self.builder.download_and_prepare( download_config=__SCREAMING_SNAKE_CASE , download_mode=__SCREAMING_SNAKE_CASE , verification_mode=__SCREAMING_SNAKE_CASE , base_path=__SCREAMING_SNAKE_CASE , num_proc=self.num_proc , ) lowerCamelCase_ : Optional[int] = self.builder.as_dataset( split="""train""" , verification_mode=__SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory ) return dataset
278
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __lowerCAmelCase ={"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class __magic_name__ ( unittest.TestCase): _UpperCAmelCase : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _UpperCAmelCase : Dict = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _UpperCAmelCase : int = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _UpperCAmelCase : int = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def _UpperCAmelCase ( self : Optional[Any] ): UpperCAmelCase = pipeline( task="text-classification" ,model="hf-internal-testing/tiny-random-distilbert" ,framework="pt" ) UpperCAmelCase = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}] ) UpperCAmelCase = text_classifier("This is great !" ,top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}] ) UpperCAmelCase = text_classifier(["This is great !", "This is bad"] ,top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[ [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], ] ,) UpperCAmelCase = text_classifier("This is great !" ,top_k=1 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}] ) # Legacy behavior UpperCAmelCase = text_classifier("This is great !" ,return_all_scores=__SCREAMING_SNAKE_CASE ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}] ) UpperCAmelCase = text_classifier("This is great !" ,return_all_scores=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]] ) UpperCAmelCase = text_classifier(["This is great !", "Something else"] ,return_all_scores=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[ [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], ] ,) UpperCAmelCase = text_classifier(["This is great !", "Something else"] ,return_all_scores=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[ {"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_0", "score": 0.504}, ] ,) @require_torch def _UpperCAmelCase ( self : Optional[Any] ): import torch UpperCAmelCase = pipeline( task="text-classification" ,model="hf-internal-testing/tiny-random-distilbert" ,framework="pt" ,device=torch.device("cpu" ) ,) UpperCAmelCase = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}] ) @require_tf def _UpperCAmelCase ( self : int ): UpperCAmelCase = pipeline( task="text-classification" ,model="hf-internal-testing/tiny-random-distilbert" ,framework="tf" ) UpperCAmelCase = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "LABEL_0", "score": 0.504}] ) @slow @require_torch def _UpperCAmelCase ( self : List[str] ): UpperCAmelCase = pipeline("text-classification" ) UpperCAmelCase = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "POSITIVE", "score": 1.0}] ) UpperCAmelCase = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "NEGATIVE", "score": 1.0}] ) UpperCAmelCase = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "POSITIVE", "score": 0.988}] ) @slow @require_tf def _UpperCAmelCase ( self : Optional[Any] ): UpperCAmelCase = pipeline("text-classification" ,framework="tf" ) UpperCAmelCase = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "POSITIVE", "score": 1.0}] ) UpperCAmelCase = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "NEGATIVE", "score": 1.0}] ) UpperCAmelCase = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": "POSITIVE", "score": 0.988}] ) def _UpperCAmelCase ( self : Dict ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : Tuple ): UpperCAmelCase = TextClassificationPipeline(model=__SCREAMING_SNAKE_CASE ,tokenizer=__SCREAMING_SNAKE_CASE ) return text_classifier, ["HuggingFace is in", "This is another test"] def _UpperCAmelCase ( self : Optional[int] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Dict ): UpperCAmelCase = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 UpperCAmelCase = "HuggingFace is in" UpperCAmelCase = text_classifier(__SCREAMING_SNAKE_CASE ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}] ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) UpperCAmelCase = ["HuggingFace is in ", "Paris is in France"] UpperCAmelCase = text_classifier(__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}, {"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}] ,) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["label"] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format UpperCAmelCase = text_classifier(__SCREAMING_SNAKE_CASE ,top_k=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[[{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}] * N, [{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}] * N] ,) UpperCAmelCase = {"text": "HuggingFace is in ", "text_pair": "Paris is in France"} UpperCAmelCase = text_classifier(__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )} ,) self.assertTrue(outputs["label"] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. UpperCAmelCase = [["HuggingFace is in ", "Paris is in France"]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): text_classifier(__SCREAMING_SNAKE_CASE ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility UpperCAmelCase = text_classifier([[["HuggingFace is in ", "Paris is in France"]]] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) ,[{"label": ANY(__SCREAMING_SNAKE_CASE ), "score": ANY(__SCREAMING_SNAKE_CASE )}] ,) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() )
333
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} a_ = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } a_ = { 'allenai/longformer-base-4096': 4_0_9_6, 'allenai/longformer-large-4096': 4_0_9_6, 'allenai/longformer-large-4096-finetuned-triviaqa': 4_0_9_6, 'allenai/longformer-base-4096-extra.pos.embd.only': 4_0_9_6, 'allenai/longformer-large-4096-extra.pos.embd.only': 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _a( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =( list(range(ord('''!''' ), ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ), ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ), ord('''ÿ''' ) + 1 ) ) ) SCREAMING_SNAKE_CASE__ : List[str] =bs[:] SCREAMING_SNAKE_CASE__ : Any =0 for b in range(2**8 ): if b not in bs: bs.append(UpperCamelCase__ ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE__ : int =[chr(UpperCamelCase__ ) for n in cs] return dict(zip(UpperCamelCase__, UpperCamelCase__ ) ) def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =set() SCREAMING_SNAKE_CASE__ : Optional[Any] =word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE__ : int =char return pairs class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[Any] , __lowercase : Union[str, Any] , __lowercase : List[Any] , __lowercase : List[Any]="replace" , __lowercase : Tuple="<s>" , __lowercase : List[Any]="</s>" , __lowercase : Any="</s>" , __lowercase : Dict="<s>" , __lowercase : Dict="<unk>" , __lowercase : Optional[Any]="<pad>" , __lowercase : Optional[int]="<mask>" , __lowercase : Union[str, Any]=False , **__lowercase : str , ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else bos_token SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else eos_token SCREAMING_SNAKE_CASE__ : int =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else sep_token SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else cls_token SCREAMING_SNAKE_CASE__ : Optional[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else unk_token SCREAMING_SNAKE_CASE__ : List[Any] =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Dict =AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token super().__init__( errors=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , add_prefix_space=__lowercase , **__lowercase , ) with open(__lowercase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE__ : str =json.load(__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] ={v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE__ : Dict =errors # how to handle errors in decoding SCREAMING_SNAKE_CASE__ : Optional[int] =bytes_to_unicode() SCREAMING_SNAKE_CASE__ : List[str] ={v: k for k, v in self.byte_encoder.items()} with open(__lowercase , encoding='''utf-8''' ) as merges_handle: SCREAMING_SNAKE_CASE__ : int =merges_handle.read().split('''\n''' )[1:-1] SCREAMING_SNAKE_CASE__ : Optional[int] =[tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE__ : Union[str, Any] =dict(zip(__lowercase , range(len(__lowercase ) ) ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] ={} SCREAMING_SNAKE_CASE__ : Optional[Any] =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE__ : Optional[Any] =re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __magic_name__ ( self : Optional[Any] ) -> List[Any]: return len(self.encoder ) def __magic_name__ ( self : Optional[int] ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : Optional[int] , __lowercase : str ) -> Tuple: if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE__ : Any =tuple(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =get_pairs(__lowercase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE__ : Any =min(__lowercase , key=lambda __lowercase : self.bpe_ranks.get(__lowercase , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =bigram SCREAMING_SNAKE_CASE__ : List[str] =[] SCREAMING_SNAKE_CASE__ : List[Any] =0 while i < len(__lowercase ): try: SCREAMING_SNAKE_CASE__ : Any =word.index(__lowercase , __lowercase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE__ : Optional[int] =j if word[i] == first and i < len(__lowercase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE__ : Tuple =tuple(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =new_word if len(__lowercase ) == 1: break else: SCREAMING_SNAKE_CASE__ : Optional[int] =get_pairs(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =''' '''.join(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =word return word def __magic_name__ ( self : Dict , __lowercase : List[Any] ) -> Any: SCREAMING_SNAKE_CASE__ : Any =[] for token in re.findall(self.pat , __lowercase ): SCREAMING_SNAKE_CASE__ : List[str] =''''''.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(__lowercase ).split(''' ''' ) ) return bpe_tokens def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[int] ) -> Optional[int]: return self.encoder.get(__lowercase , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Tuple , __lowercase : Dict ) -> Any: return self.decoder.get(__lowercase ) def __magic_name__ ( self : Any , __lowercase : str ) -> Any: SCREAMING_SNAKE_CASE__ : List[Any] =''''''.join(__lowercase ) SCREAMING_SNAKE_CASE__ : int =bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __magic_name__ ( self : Optional[int] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE__ : Dict =os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE__ : Dict =os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowercase , ensure_ascii=__lowercase ) + '''\n''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =0 with open(__lowercase , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowercase : kv[1] ): if index != token_index: logger.warning( F"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ''' Please check that the tokenizer is not corrupted!''' ) SCREAMING_SNAKE_CASE__ : Dict =token_index writer.write(''' '''.join(__lowercase ) + '''\n''' ) index += 1 return vocab_file, merge_file def __magic_name__ ( self : Any , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str =[self.cls_token_id] SCREAMING_SNAKE_CASE__ : List[str] =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __magic_name__ ( self : List[str] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None , __lowercase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] def __magic_name__ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ : Tuple =[self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __magic_name__ ( self : Tuple , __lowercase : Union[str, Any] , __lowercase : Optional[int]=False , **__lowercase : List[str] ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] =kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowercase ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE__ : int =''' ''' + text return (text, kwargs)
665
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase , unittest.TestCase ): snake_case_ = SpeechTaTokenizer snake_case_ = False snake_case_ = True def __magic_name__ ( self : int ) -> Any: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[Any] =SpeechTaTokenizer(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =AddedToken('''<mask>''' , lstrip=__lowercase , rstrip=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__ ( self : Dict , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] ='''this is a test''' SCREAMING_SNAKE_CASE__ : int ='''this is a test''' return input_text, output_text def __magic_name__ ( self : List[Any] , __lowercase : int , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=20 , __lowercase : Any=5 ) -> Any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int =self.get_input_output_texts(__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) SCREAMING_SNAKE_CASE__ : str =tokenizer.decode(__lowercase , clean_up_tokenization_spaces=__lowercase ) return text, ids def __magic_name__ ( self : Dict ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] ='''<pad>''' SCREAMING_SNAKE_CASE__ : Optional[int] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def __magic_name__ ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__lowercase ) , 81 ) def __magic_name__ ( self : Dict ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __magic_name__ ( self : Optional[Any] ) -> str: SCREAMING_SNAKE_CASE__ : str =self.get_tokenizers(do_lower_case=__lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Any =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ : int =['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.add_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : Tuple =tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ : str ={'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} SCREAMING_SNAKE_CASE__ : int =tokenizer.add_special_tokens(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =tokenizer.vocab_size SCREAMING_SNAKE_CASE__ : int =len(__lowercase ) self.assertNotEqual(__lowercase , 0 ) self.assertEqual(__lowercase , __lowercase ) self.assertEqual(__lowercase , len(__lowercase ) ) self.assertEqual(__lowercase , all_size_a + len(__lowercase ) ) SCREAMING_SNAKE_CASE__ : List[Any] =tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__lowercase ) self.assertGreaterEqual(len(__lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __magic_name__ ( self : Optional[Any] ) -> Any: pass def __magic_name__ ( self : List[str] ) -> List[Any]: pass def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] =tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =tokenizer.convert_tokens_to_ids(__lowercase ) # fmt: off self.assertListEqual(__lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] =tokenizer.convert_ids_to_tokens(__lowercase ) self.assertListEqual( __lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __magic_name__ ( self : List[str] ) -> List[str]: # Use custom sequence because this tokenizer does not handle numbers. SCREAMING_SNAKE_CASE__ : List[Any] =[ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off SCREAMING_SNAKE_CASE__ : str ={ '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__lowercase , )
665
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer lowerCAmelCase :str = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase :Union[str, Any] = { '''vocab_file''': { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt''', }, '''tokenizer_file''': { '''unc-nlp/lxmert-base-uncased''': ( '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json''' ), }, } lowerCAmelCase :List[Any] = { '''unc-nlp/lxmert-base-uncased''': 5_1_2, } lowerCAmelCase :int = { '''unc-nlp/lxmert-base-uncased''': {'''do_lower_case''': True}, } class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : Dict = VOCAB_FILES_NAMES A_ : Dict = PRETRAINED_VOCAB_FILES_MAP A_ : Optional[int] = PRETRAINED_INIT_CONFIGURATION A_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Dict = LxmertTokenizer def __init__( self : List[str] , _A : Union[str, Any]=None , _A : Optional[Any]=None , _A : Dict=True , _A : Optional[Any]="[UNK]" , _A : Any="[SEP]" , _A : Union[str, Any]="[PAD]" , _A : Union[str, Any]="[CLS]" , _A : Tuple="[MASK]" , _A : Union[str, Any]=True , _A : Optional[Any]=None , **_A : Union[str, Any] , ) -> List[Any]: super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __magic_name__ : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __magic_name__ : int = getattr(_A , normalizer_state.pop('type' ) ) __magic_name__ : str = do_lower_case __magic_name__ : int = strip_accents __magic_name__ : Any = tokenize_chinese_chars __magic_name__ : Optional[Any] = normalizer_class(**_A ) __magic_name__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , _A : List[str] , _A : Dict=None ) -> Tuple: __magic_name__ : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[str] , _A : List[int] , _A : Optional[List[int]] = None ) -> List[int]: __magic_name__ : Any = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : Optional[str] = None ) -> Tuple[str]: __magic_name__ : Optional[Any] = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
561
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) -> Dict: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights __magic_name__ : Optional[int] = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_A , cache_dir=_A ) __magic_name__ : Any = [t[-1] for t in os.walk(os.path.join(_A , os.listdir(_A )[0] , 'snapshots' ) )] __magic_name__ : Optional[int] = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) -> List[Any]: __magic_name__ , __magic_name__ : Any = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_A ) __magic_name__ : Optional[Any] = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : List[Any] = jax.random.PRNGKey(0 ) __magic_name__ : Optional[Any] = 4 __magic_name__ : str = jax.device_count() __magic_name__ : Any = num_samples * [prompt] __magic_name__ : Union[str, Any] = pipeline.prepare_inputs(_A ) # shard inputs and rng __magic_name__ : Optional[Any] = replicate(_A ) __magic_name__ : Dict = jax.random.split(_A , _A ) __magic_name__ : Union[str, Any] = shard(_A ) __magic_name__ : Union[str, Any] = pipeline(_A , _A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.151_4745 ) < 1E-3 assert np.abs(np.abs(_A , dtype=np.floataa ).sum() - 4_9947.875 ) < 5E-1 __magic_name__ : Optional[int] = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_A ) == num_samples def __lowerCAmelCase ( self : str ) -> Optional[int]: __magic_name__ , __magic_name__ : Any = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_A ) __magic_name__ : Any = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : int = jax.random.PRNGKey(0 ) __magic_name__ : Tuple = 50 __magic_name__ : Any = jax.device_count() __magic_name__ : Dict = num_samples * [prompt] __magic_name__ : List[Any] = pipeline.prepare_inputs(_A ) # shard inputs and rng __magic_name__ : str = replicate(_A ) __magic_name__ : Any = jax.random.split(_A , _A ) __magic_name__ : Optional[Any] = shard(_A ) __magic_name__ : Optional[Any] = pipeline(_A , _A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0565_2401) ) < 1E-3 assert np.abs((np.abs(_A , dtype=np.floataa ).sum() - 238_3808.2) ) < 5E-1 def __lowerCAmelCase ( self : Optional[int] ) -> List[str]: __magic_name__ , __magic_name__ : List[Any] = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_A ) __magic_name__ : List[str] = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : List[str] = jax.random.PRNGKey(0 ) __magic_name__ : int = 50 __magic_name__ : Optional[Any] = jax.device_count() __magic_name__ : int = num_samples * [prompt] __magic_name__ : int = pipeline.prepare_inputs(_A ) # shard inputs and rng __magic_name__ : int = replicate(_A ) __magic_name__ : List[Any] = jax.random.split(_A , _A ) __magic_name__ : Optional[int] = shard(_A ) __magic_name__ : Union[str, Any] = pipeline(_A , _A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0400_3906) ) < 1E-3 assert np.abs((np.abs(_A , dtype=np.floataa ).sum() - 237_3516.75) ) < 5E-1 def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: __magic_name__ , __magic_name__ : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) __magic_name__ : Dict = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : int = jax.random.PRNGKey(0 ) __magic_name__ : Tuple = 50 __magic_name__ : int = jax.device_count() __magic_name__ : Union[str, Any] = num_samples * [prompt] __magic_name__ : Dict = pipeline.prepare_inputs(_A ) # shard inputs and rng __magic_name__ : List[str] = replicate(_A ) __magic_name__ : str = jax.random.split(_A , _A ) __magic_name__ : Tuple = shard(_A ) __magic_name__ : Optional[Any] = pipeline(_A , _A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0400_3906) ) < 1E-3 assert np.abs((np.abs(_A , dtype=np.floataa ).sum() - 237_3516.75) ) < 5E-1 def __lowerCAmelCase ( self : str ) -> Tuple: __magic_name__ : List[str] = FlaxDDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_A , steps_offset=1 , ) __magic_name__ , __magic_name__ : str = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_A , safety_checker=_A , ) __magic_name__ : Tuple = scheduler.create_state() __magic_name__ : Optional[Any] = scheduler_state __magic_name__ : str = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : Dict = jax.random.PRNGKey(0 ) __magic_name__ : List[Any] = 50 __magic_name__ : Any = jax.device_count() __magic_name__ : List[str] = num_samples * [prompt] __magic_name__ : List[Any] = pipeline.prepare_inputs(_A ) # shard inputs and rng __magic_name__ : Union[str, Any] = replicate(_A ) __magic_name__ : Tuple = jax.random.split(_A , _A ) __magic_name__ : str = shard(_A ) __magic_name__ : int = pipeline(_A , _A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_4504_3945) ) < 1E-3 assert np.abs((np.abs(_A , dtype=np.floataa ).sum() - 234_7693.5) ) < 5E-1 def __lowerCAmelCase ( self : Optional[Any] ) -> List[str]: __magic_name__ : Optional[int] = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) __magic_name__ : Union[str, Any] = jax.device_count() __magic_name__ : Optional[Any] = num_samples * [prompt] __magic_name__ : Dict = jax.random.split(jax.random.PRNGKey(0 ) , _A ) __magic_name__ , __magic_name__ : List[Any] = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_A , ) __magic_name__ : Union[str, Any] = replicate(_A ) __magic_name__ : Tuple = pipeline.prepare_inputs(_A ) __magic_name__ : Union[str, Any] = shard(_A ) __magic_name__ : str = pipeline(_A , _A , _A , jit=_A ).images assert images.shape == (num_samples, 1, 512, 512, 3) __magic_name__ : Optional[int] = images[2, 0, 256, 10:17, 1] # With memory efficient attention __magic_name__ , __magic_name__ : Any = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_A , use_memory_efficient_attention=_A , ) __magic_name__ : List[Any] = replicate(_A ) __magic_name__ : Optional[int] = pipeline.prepare_inputs(_A ) __magic_name__ : Tuple = shard(_A ) __magic_name__ : Dict = pipeline(_A , _A , _A , jit=_A ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) __magic_name__ : Dict = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
561
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case : Optional[Any] = {'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Dict = [ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __snake_case : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
721
"""simple docstring""" import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) __snake_case : str = pytest.mark.integration @pytest.mark.parametrize("path" ,["paws", "csv"] ) def _lowercase ( __snake_case ,__snake_case ) -> Any: inspect_dataset(__snake_case ,__snake_case ) __lowerCAmelCase : str = path + ".py" assert script_name in os.listdir(__snake_case ) assert "__pycache__" not in os.listdir(__snake_case ) @pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.parametrize("path" ,["accuracy"] ) def _lowercase ( __snake_case ,__snake_case ) -> int: inspect_metric(__snake_case ,__snake_case ) __lowerCAmelCase : str = path + ".py" assert script_name in os.listdir(__snake_case ) assert "__pycache__" not in os.listdir(__snake_case ) @pytest.mark.parametrize( "path, config_name, expected_splits" ,[ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] ,) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Optional[int]: __lowerCAmelCase : str = get_dataset_config_info(__snake_case ,config_name=__snake_case ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" ,[ ("paws", None, ValueError), ] ,) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> List[str]: with pytest.raises(__snake_case ): get_dataset_config_info(__snake_case ,config_name=__snake_case ) @pytest.mark.parametrize( "path, expected" ,[ ("squad", "plain_text"), ("acronym_identification", "default"), ("lhoestq/squad", "plain_text"), ("lhoestq/test", "default"), ("lhoestq/demo1", "lhoestq--demo1"), ("dalle-mini/wit", "dalle-mini--wit"), ] ,) def _lowercase ( __snake_case ,__snake_case ) -> int: __lowerCAmelCase : Dict = get_dataset_config_names(__snake_case ) assert expected in config_names @pytest.mark.parametrize( "path, expected_configs, expected_splits_in_first_config" ,[ ("squad", ["plain_text"], ["train", "validation"]), ("dalle-mini/wit", ["dalle-mini--wit"], ["train"]), ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]), ] ,) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Optional[Any]: __lowerCAmelCase : List[Any] = get_dataset_infos(__snake_case ) assert list(infos.keys() ) == expected_configs __lowerCAmelCase : List[Any] = expected_configs[0] assert expected_config in infos __lowerCAmelCase : Tuple = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( "path, expected_config, expected_splits" ,[ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] ,) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Union[str, Any]: __lowerCAmelCase : Tuple = get_dataset_infos(__snake_case ) assert expected_config in infos __lowerCAmelCase : int = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" ,[ ("paws", None, ValueError), ] ,) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Any: with pytest.raises(__snake_case ): get_dataset_split_names(__snake_case ,config_name=__snake_case )
615
0
def a__ ( snake_case , snake_case , snake_case = 0 , snake_case = 0 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = right or len(snake_case ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(snake_case , snake_case , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def _snake_case ( UpperCamelCase : List[str] , UpperCamelCase : Any , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] ): # Initialise PyTorch model UpperCAmelCase : int = FunnelConfig.from_json_file(UpperCamelCase ) print(F"Building PyTorch model from configuration: {config}" ) UpperCAmelCase : Dict = FunnelBaseModel(UpperCamelCase ) if base_model else FunnelModel(UpperCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_funnel(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , UpperCamelCase ) if __name__ == "__main__": A: str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." ) A: Tuple = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
160
0
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __SCREAMING_SNAKE_CASE : __a =42 __a =None __a =None def __UpperCAmelCase ( ) -> Union[str, Any]: """simple docstring""" __a = Node(1 ) __a = Node(2 ) __a = Node(3 ) __a = Node(4 ) __a = Node(5 ) return tree def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> Any: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> Union[str, Any]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> str: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> Tuple: """simple docstring""" return (max(height(root.left ), height(root.right ) ) + 1) if root else 0 def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> Optional[Any]: """simple docstring""" __a = [] if root is None: return output __a = deque([root] ) while process_queue: __a = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None, SCREAMING_SNAKE_CASE__: int ) -> str: """simple docstring""" __a = [] def populate_output(SCREAMING_SNAKE_CASE__: Node | None, SCREAMING_SNAKE_CASE__: int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left, level - 1 ) populate_output(root.right, level - 1 ) populate_output(snake_case__, snake_case__ ) return output def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None, SCREAMING_SNAKE_CASE__: int ) -> Optional[Any]: """simple docstring""" __a = [] def populate_output(SCREAMING_SNAKE_CASE__: Node | None, SCREAMING_SNAKE_CASE__: int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right, level - 1 ) populate_output(root.left, level - 1 ) populate_output(snake_case__, snake_case__ ) return output def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Node | None ) -> Union[str, Any]: """simple docstring""" if root is None: return [] __a = [] __a = 0 __a = height(snake_case__ ) for h in range(1, height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(snake_case__, snake_case__ ) ) __a = 1 else: output.append(get_nodes_from_right_to_left(snake_case__, snake_case__ ) ) __a = 0 return output def __UpperCAmelCase ( ) -> Any: # Main function for testing. """simple docstring""" __a = make_tree() print(f"""In-order Traversal: {inorder(snake_case__ )}""" ) print(f"""Pre-order Traversal: {preorder(snake_case__ )}""" ) print(f"""Post-order Traversal: {postorder(snake_case__ )}""", '\n' ) print(f"""Height of Tree: {height(snake_case__ )}""", '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(snake_case__ ), '\n' ) print('Level-wise order Traversal: ' ) for level in range(1, height(snake_case__ ) + 1 ): print(f"""Level {level}:""", get_nodes_from_left_to_right(snake_case__, level=snake_case__ ) ) print('\nZigZag order Traversal: ' ) print(zigzag(snake_case__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
706
'''simple docstring''' __UpperCamelCase : Optional[Any] = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
270
0
"""simple docstring""" def lowerCamelCase (a_ :list[int] , a_ :list[int]) -> None: lowercase :Optional[int] = len(a_) print('''The following activities are selected:''') # The first activity is always selected lowercase :Dict = 0 print(a_ , end=''',''') # Consider rest of the activities for j in range(a_): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(a_ , end=''',''') lowercase :str = j if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase = [1, 3, 0, 5, 8, 5] UpperCAmelCase = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
677
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets UpperCAmelCase = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' UpperCAmelCase = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' UpperCAmelCase = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def __snake_case ( self : int ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def __snake_case ( self : Optional[Any] ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def __snake_case ( self : List[Any] , snake_case__ : str , snake_case__ : int , snake_case__ : str=None , snake_case__ : List[Any]="uniform_average" , snake_case__ : Dict=True ): '''simple docstring''' lowercase :Dict = mean_squared_error( snake_case__ , snake_case__ , sample_weight=snake_case__ , multioutput=snake_case__ , squared=snake_case__ ) return {"mse": mse}
677
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { """configuration_xlm_roberta_xl""": [ """XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMRobertaXLConfig""", """XLMRobertaXLOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMRobertaXLForCausalLM""", """XLMRobertaXLForMaskedLM""", """XLMRobertaXLForMultipleChoice""", """XLMRobertaXLForQuestionAnswering""", """XLMRobertaXLForSequenceClassification""", """XLMRobertaXLForTokenClassification""", """XLMRobertaXLModel""", """XLMRobertaXLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
560
"""simple docstring""" import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __A (_SCREAMING_SNAKE_CASE ) ->float: """simple docstring""" return np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) class _lowerCAmelCase : """simple docstring""" def __init__( self , *, __UpperCAmelCase = np.inf , __UpperCAmelCase = "linear" , __UpperCAmelCase = 0.0 , ): '''simple docstring''' lowerCAmelCase__ :str = regularization lowerCAmelCase__ :Optional[int] = gamma if kernel == "linear": lowerCAmelCase__ :Union[str, Any] = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('rbf kernel requires gamma' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('gamma must be float or int' ) if not self.gamma > 0: raise ValueError('gamma must be > 0' ) lowerCAmelCase__ :int = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCAmelCase__ :Dict = F"Unknown kernel: {kernel}" raise ValueError(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return np.dot(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = observations lowerCAmelCase__ :int = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCAmelCase__) , ) :Union[str, Any] = np.shape(__UpperCAmelCase ) def to_minimize(__UpperCAmelCase ) -> float: lowerCAmelCase__ :Optional[Any] = 0 ((lowerCAmelCase__) , ) :Optional[int] = np.shape(__UpperCAmelCase ) for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = LinearConstraint(__UpperCAmelCase , 0 , 0 ) lowerCAmelCase__ :Optional[Any] = Bounds(0 , self.regularization ) lowerCAmelCase__ :Dict = minimize( __UpperCAmelCase , np.ones(__UpperCAmelCase ) , bounds=__UpperCAmelCase , constraints=[ly_contraint] ).x lowerCAmelCase__ :Optional[int] = l_star # calculating mean offset of separation plane to points lowerCAmelCase__ :Tuple = 0 for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) lowerCAmelCase__ :int = s / n def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __UpperCAmelCase ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
560
1
"""simple docstring""" import os def _snake_case ( snake_case__ : str = "input.txt" ): with open(os.path.join(os.path.dirname(snake_case__ ) , snake_case__ ) ) as input_file: A = [ [int(snake_case__ ) for element in line.split(',' )] for line in input_file.readlines() ] A = len(snake_case__ ) A = len(matrix[0] ) A = [[-1 for _ in range(snake_case__ )] for _ in range(snake_case__ )] for i in range(snake_case__ ): A = matrix[i][0] for j in range(1 , snake_case__ ): for i in range(snake_case__ ): A = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , snake_case__ ): A = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): A = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F"""{solution() = }""")
91
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 _SCREAMING_SNAKE_CASE : List[Any] = imread(r'''digital_image_processing/image_data/lena_small.jpg''') _SCREAMING_SNAKE_CASE : Tuple = cvtColor(img, COLOR_BGR2GRAY) def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = cn.convert_to_negative(_A ) # assert negative_img array for at least one True assert negative_img.any() def UpperCAmelCase_ ( ): '''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(_A , 1_10 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ = canny.canny(_A ) # assert canny array for at least one True assert canny_array.any() def UpperCAmelCase_ ( ): '''simple docstring''' assert gg.gaussian_filter(_A , 5 , sigma=0.9 ).all() def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = array([[0.2_5, 0.5, 0.2_5], [0.5, -3, 0.5], [0.2_5, 0.5, 0.2_5]] ) SCREAMING_SNAKE_CASE__ = conv.img_convolve(_A , _A ).astype(_A ) assert res.any() def UpperCAmelCase_ ( ): '''simple docstring''' assert med.median_filter(_A , 3 ).any() def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = sob.sobel_filter(_A ) assert grad.any() and theta.any() def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = sp.make_sepia(_A , 20 ) assert sepia.all() def UpperCAmelCase_ ( _A = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = bs.Burkes(imread(_A , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def UpperCAmelCase_ ( _A = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = rs.NearestNeighbour(imread(_A , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ = imread(_A , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ = lbp.get_neighbors_pixel( _A , _A , _A , _A ) 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 SCREAMING_SNAKE_CASE__ = 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] ): SCREAMING_SNAKE_CASE__ = lbp.local_binary_value(_A , _A , _A ) assert lbp_image.any()
493
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ =get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class __UpperCamelCase ( _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __a : Optional[Any] =XLMRobertaTokenizer __a : Any =XLMRobertaTokenizerFast __a : Optional[int] =True __a : str =True def __snake_case ( self ): super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase = XLMRobertaTokenizer(_UpperCAmelCase , keep_accents=_UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self ): lowerCAmelCase = '''<pad>''' lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) , _UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) , _UpperCAmelCase ) def __snake_case ( self ): lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(_UpperCAmelCase ) , 10_02 ) def __snake_case ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def __snake_case ( self ): lowerCAmelCase = XLMRobertaTokenizer(_UpperCAmelCase , keep_accents=_UpperCAmelCase ) lowerCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) lowerCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) lowerCAmelCase = tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) self.assertListEqual( _UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCAmelCase = tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) self.assertListEqual( _UpperCAmelCase , [ 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 __snake_case ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCAmelCase = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-xlm-roberta''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase , **_UpperCAmelCase ) lowerCAmelCase = self.tokenizer_class.from_pretrained(_UpperCAmelCase , **_UpperCAmelCase ) lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.save_pretrained(_UpperCAmelCase ) # 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 ) ) lowerCAmelCase = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(_UpperCAmelCase , _UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase = tokenizer_r.from_pretrained(_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.from_pretrained(_UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_UpperCAmelCase , _UpperCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(_UpperCAmelCase ) # Save tokenizer rust, legacy_format=True lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(_UpperCAmelCase , legacy_format=_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.save_pretrained(_UpperCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(_UpperCAmelCase , _UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase = tokenizer_r.from_pretrained(_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.from_pretrained(_UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_UpperCAmelCase , _UpperCAmelCase ) ) shutil.rmtree(_UpperCAmelCase ) # Save tokenizer rust, legacy_format=False lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(_UpperCAmelCase , legacy_format=_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.save_pretrained(_UpperCAmelCase ) # 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 lowerCAmelCase = tokenizer_r.from_pretrained(_UpperCAmelCase ) lowerCAmelCase = tokenizer_p.from_pretrained(_UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_UpperCAmelCase , _UpperCAmelCase ) ) shutil.rmtree(_UpperCAmelCase ) @cached_property def __snake_case ( self ): return XLMRobertaTokenizer.from_pretrained('''xlm-roberta-base''' ) def __snake_case ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(_UpperCAmelCase , f.name ) lowerCAmelCase = XLMRobertaTokenizer(f.name , keep_accents=_UpperCAmelCase ) lowerCAmelCase = pickle.dumps(_UpperCAmelCase ) pickle.loads(_UpperCAmelCase ) def __snake_case ( self ): if not self.test_rust_tokenizer: return lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = '''I was born in 92000, and this is falsé.''' lowerCAmelCase = tokenizer.tokenize(_UpperCAmelCase ) lowerCAmelCase = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) lowerCAmelCase = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ) lowerCAmelCase = rust_tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = tokenizer.encode(_UpperCAmelCase ) lowerCAmelCase = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) @slow def __snake_case ( self ): lowerCAmelCase = '''Hello World!''' lowerCAmelCase = [0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(_UpperCAmelCase , self.big_tokenizer.encode(_UpperCAmelCase ) ) @slow def __snake_case ( self ): lowerCAmelCase = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) lowerCAmelCase = [ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(_UpperCAmelCase , self.big_tokenizer.encode(_UpperCAmelCase ) ) @slow def __snake_case ( self ): # fmt: off lowerCAmelCase = {'''input_ids''': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase , model_name='''xlm-roberta-base''' , revision='''d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3''' , )
712
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase_ =logging.get_logger(__name__) class __UpperCamelCase ( __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' __a : Optional[Any] ="""maskformer-swin""" __a : Optional[int] ={ """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , UpperCAmelCase_=2_24 , UpperCAmelCase_=4 , UpperCAmelCase_=3 , UpperCAmelCase_=96 , UpperCAmelCase_=[2, 2, 6, 2] , UpperCAmelCase_=[3, 6, 12, 24] , UpperCAmelCase_=7 , UpperCAmelCase_=4.0 , UpperCAmelCase_=True , UpperCAmelCase_=0.0 , UpperCAmelCase_=0.0 , UpperCAmelCase_=0.1 , UpperCAmelCase_="gelu" , UpperCAmelCase_=False , UpperCAmelCase_=0.02 , UpperCAmelCase_=1E-5 , UpperCAmelCase_=None , UpperCAmelCase_=None , **UpperCAmelCase_ , ): super().__init__(**UpperCAmelCase_ ) lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = embed_dim lowerCAmelCase = depths lowerCAmelCase = len(UpperCAmelCase_ ) lowerCAmelCase = num_heads lowerCAmelCase = window_size lowerCAmelCase = mlp_ratio lowerCAmelCase = qkv_bias lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = drop_path_rate lowerCAmelCase = hidden_act lowerCAmelCase = use_absolute_embeddings lowerCAmelCase = layer_norm_eps lowerCAmelCase = 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 lowerCAmelCase = int(embed_dim * 2 ** (len(UpperCAmelCase_ ) - 1) ) lowerCAmelCase = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(UpperCAmelCase_ ) + 1 )] lowerCAmelCase , lowerCAmelCase = get_aligned_output_features_output_indices( out_features=UpperCAmelCase_ , out_indices=UpperCAmelCase_ , stage_names=self.stage_names )
33
0
from __future__ import annotations from random import choice def a_ ( __lowerCAmelCase ): return choice(__lowerCAmelCase ) def a_ ( __lowerCAmelCase , __lowerCAmelCase ): lowerCAmelCase__ = random_pivot(__lowerCAmelCase ) # partition based on pivot # linear time lowerCAmelCase__ = [e for e in lst if e < pivot] lowerCAmelCase__ = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__lowerCAmelCase ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__lowerCAmelCase ) < k - 1: return kth_number(__lowerCAmelCase , k - len(__lowerCAmelCase ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
615
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ : Optional[int] = { """configuration_biogpt""": ["""BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BioGptConfig"""], """tokenization_biogpt""": ["""BioGptTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int = [ """BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BioGptForCausalLM""", """BioGptForTokenClassification""", """BioGptForSequenceClassification""", """BioGptModel""", """BioGptPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __magic_name__ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
615
1
'''simple docstring''' def UpperCamelCase_ ( A__ : int , A__ : int ): '''simple docstring''' while a != 0: lowerCAmelCase_, lowerCAmelCase_ : Union[str, Any] = b % a, a return b def UpperCamelCase_ ( A__ : int , A__ : int ): '''simple docstring''' if gcd(UpperCAmelCase__ , UpperCAmelCase__ ) != 1: lowerCAmelCase_ : Dict = f'mod inverse of {a!r} and {m!r} does not exist' raise ValueError(UpperCAmelCase__ ) lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ : str = 1, 0, a lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ : List[Any] = 0, 1, m while va != 0: lowerCAmelCase_ : List[Any] = ua // va lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ : Optional[int] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
715
'''simple docstring''' from __future__ import annotations __A : List[Any] = "#" class __snake_case : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase_ : dict = {} def __lowercase ( self : Any , lowerCamelCase : str ) -> None: lowerCAmelCase_ : Optional[int] = self._trie for char in text: if char not in trie: lowerCAmelCase_ : List[Any] = {} lowerCAmelCase_ : Optional[Any] = trie[char] lowerCAmelCase_ : Any = True def __lowercase ( self : Dict , lowerCamelCase : str ) -> tuple | list: lowerCAmelCase_ : List[Any] = self._trie for char in prefix: if char in trie: lowerCAmelCase_ : List[str] = trie[char] else: return [] return self._elements(lowerCamelCase ) def __lowercase ( self : str , lowerCamelCase : dict ) -> tuple: lowerCAmelCase_ : List[str] = [] for c, v in d.items(): lowerCAmelCase_ : Optional[int] = [""" """] if c == END else [(c + s) for s in self._elements(lowerCamelCase )] result.extend(lowerCamelCase ) return tuple(lowerCamelCase ) __A : Optional[int] = Trie() __A : Dict = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def UpperCamelCase_ ( A__ : str ): '''simple docstring''' lowerCAmelCase_ : int = trie.find_word(A__ ) return tuple(string + word for word in suffixes ) def UpperCamelCase_ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
398
0
from math import pow def _UpperCamelCase ( snake_case__, snake_case__, snake_case__, snake_case__, snake_case__, ) -> tuple[int, int]: if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count __UpperCAmelCase : Tuple = int(pow(snake_case__, snake_case__ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n __UpperCAmelCase , __UpperCAmelCase : str = backtrack( snake_case__, snake_case__, current_number + 1, snake_case__, snake_case__ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = backtrack( snake_case__, snake_case__, current_number + 1, snake_case__, snake_case__ ) return current_sum, solutions_count def _UpperCamelCase ( snake_case__, snake_case__ ) -> int: if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( "Invalid input\n" "needed_sum must be between 1 and 1000, power between 2 and 10." ) return backtrack(snake_case__, snake_case__, 1, 0, 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
382
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _snake_case ( _lowercase ): lowerCamelCase__: Optional[int] = "audio-spectrogram-transformer" def __init__( self: Any , __lowerCamelCase: Union[str, Any]=7_68 , __lowerCamelCase: List[str]=12 , __lowerCamelCase: Optional[Any]=12 , __lowerCamelCase: Optional[int]=30_72 , __lowerCamelCase: Optional[Any]="gelu" , __lowerCamelCase: Dict=0.0 , __lowerCamelCase: Optional[Any]=0.0 , __lowerCamelCase: Tuple=0.02 , __lowerCamelCase: List[Any]=1e-12 , __lowerCamelCase: Tuple=16 , __lowerCamelCase: Optional[Any]=True , __lowerCamelCase: Optional[Any]=10 , __lowerCamelCase: str=10 , __lowerCamelCase: Any=10_24 , __lowerCamelCase: Dict=1_28 , **__lowerCamelCase: Optional[Any] , ) -> List[str]: super().__init__(**__lowerCamelCase ) __UpperCAmelCase : str = hidden_size __UpperCAmelCase : Any = num_hidden_layers __UpperCAmelCase : Any = num_attention_heads __UpperCAmelCase : List[str] = intermediate_size __UpperCAmelCase : Optional[Any] = hidden_act __UpperCAmelCase : int = hidden_dropout_prob __UpperCAmelCase : Dict = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = initializer_range __UpperCAmelCase : str = layer_norm_eps __UpperCAmelCase : int = patch_size __UpperCAmelCase : Any = qkv_bias __UpperCAmelCase : str = frequency_stride __UpperCAmelCase : Union[str, Any] = time_stride __UpperCAmelCase : Dict = max_length __UpperCAmelCase : Optional[Any] = num_mel_bins
382
1
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) __a : List[Any] = logging.getLogger() def UpperCAmelCase ( ): """simple docstring""" __lowercase = argparse.ArgumentParser() parser.add_argument('''-f''' ) __lowercase = parser.parse_args() return args.f def UpperCAmelCase ( lowercase ): """simple docstring""" __lowercase = {} __lowercase = os.path.join(lowercase , '''all_results.json''' ) if os.path.exists(lowercase ): with open(lowercase , '''r''' ) as f: __lowercase = json.load(lowercase ) else: raise ValueError(F"can't find {path}" ) return results def UpperCAmelCase ( ): """simple docstring""" __lowercase = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() __a : Any = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( __lowerCAmelCase ): """simple docstring""" @classmethod def _SCREAMING_SNAKE_CASE ( cls ) -> List[Any]: '''simple docstring''' __lowercase = tempfile.mkdtemp() __lowercase = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __lowercase = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def _SCREAMING_SNAKE_CASE ( cls ) -> Dict: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n ".split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n ".split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertLess(result['''perplexity'''] , 1_00 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = 7 if get_gpu_count() > 1 else 2 __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['''eval_f1'''] , 28 ) self.assertGreaterEqual(result['''eval_exact'''] , 28 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_rouge1'''] , 10 ) self.assertGreaterEqual(result['''eval_rouge2'''] , 2 ) self.assertGreaterEqual(result['''eval_rougeL'''] , 7 ) self.assertGreaterEqual(result['''eval_rougeLsum'''] , 7 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''translation_no_trainer''' ) ) ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' __lowercase = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase__ ) __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n ".split() run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F"\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n ".split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) __lowercase = get_results(lowerCamelCase__ ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__ , '''image_classification_no_trainer''' ) ) )
718
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( _UpperCAmelCase ): """simple docstring""" __a : Tuple = ['''image_processor''', '''tokenizer'''] __a : Dict = '''AutoImageProcessor''' __a : List[Any] = '''AutoTokenizer''' def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) __lowercase = self.image_processor def __call__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: __lowercase = self.tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ ) if images is not None: __lowercase = self.image_processor(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ ) if text is not None and images is not None: __lowercase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowerCAmelCase__ ) , tensor_type=lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> str: '''simple docstring''' return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) @property def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
522
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def a ( snake_case__: Union[str, Any] , snake_case__: Tuple , snake_case__: List[Any] ): '''simple docstring''' return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def a ( snake_case__: Tuple , snake_case__: List[Any] , snake_case__: Dict , snake_case__: str="attention" ): '''simple docstring''' lowercase_ = lowercase_ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) lowercase_ = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) lowercase_ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) lowercase_ = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) lowercase_ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) lowercase_ = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) lowercase_ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) lowercase_ = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def a ( snake_case__: int , snake_case__: int , snake_case__: Any , snake_case__: Optional[int]=False ): '''simple docstring''' if split_mlp_wi: lowercase_ = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] lowercase_ = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] lowercase_ = (wi_a, wi_a) else: lowercase_ = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] lowercase_ = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def a ( snake_case__: str , snake_case__: Optional[Any] , snake_case__: List[str] , snake_case__: Tuple ): '''simple docstring''' return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def a ( snake_case__: dict , *, snake_case__: int , snake_case__: bool , snake_case__: bool = False ): '''simple docstring''' lowercase_ = traverse_util.flatten_dict(variables['''target'''] ) lowercase_ = {'''/'''.join(snake_case__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi lowercase_ = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''' , snake_case__ ) lowercase_ = collections.OrderedDict() # Shared embeddings. lowercase_ = old['''token_embedder/embedding'''] # Encoder. for i in range(snake_case__ ): # Block i, layer 0 (Self Attention). lowercase_ = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''encoder''' , '''pre_attention_layer_norm''' ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = tax_attention_lookup(snake_case__ , snake_case__ , '''encoder''' , '''attention''' ) lowercase_ = layer_norm lowercase_ = k.T lowercase_ = o.T lowercase_ = q.T lowercase_ = v.T # Block i, layer 1 (MLP). lowercase_ = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''encoder''' , '''pre_mlp_layer_norm''' ) lowercase_ , lowercase_ = tax_mlp_lookup(snake_case__ , snake_case__ , '''encoder''' , snake_case__ ) lowercase_ = layer_norm if split_mlp_wi: lowercase_ = wi[0].T lowercase_ = wi[1].T else: lowercase_ = wi.T lowercase_ = wo.T if scalable_attention: # convert the rel_embedding of each layer lowercase_ = tax_relpos_bias_lookup( snake_case__ , snake_case__ , '''encoder''' ).T lowercase_ = old['''encoder/encoder_norm/scale'''] if not scalable_attention: lowercase_ = tax_relpos_bias_lookup( snake_case__ , 0 , '''encoder''' ).T lowercase_ = tax_relpos_bias_lookup( snake_case__ , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(snake_case__ ): # Block i, layer 0 (Self Attention). lowercase_ = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_self_attention_layer_norm''' ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = tax_attention_lookup(snake_case__ , snake_case__ , '''decoder''' , '''self_attention''' ) lowercase_ = layer_norm lowercase_ = k.T lowercase_ = o.T lowercase_ = q.T lowercase_ = v.T # Block i, layer 1 (Cross Attention). lowercase_ = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = tax_attention_lookup(snake_case__ , snake_case__ , '''decoder''' , '''encoder_decoder_attention''' ) lowercase_ = layer_norm lowercase_ = k.T lowercase_ = o.T lowercase_ = q.T lowercase_ = v.T # Block i, layer 2 (MLP). lowercase_ = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_mlp_layer_norm''' ) lowercase_ , lowercase_ = tax_mlp_lookup(snake_case__ , snake_case__ , '''decoder''' , snake_case__ ) lowercase_ = layer_norm if split_mlp_wi: lowercase_ = wi[0].T lowercase_ = wi[1].T else: lowercase_ = wi.T lowercase_ = wo.T if scalable_attention: # convert the rel_embedding of each layer lowercase_ = tax_relpos_bias_lookup(snake_case__ , snake_case__ , '''decoder''' ).T lowercase_ = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: lowercase_ = old['''decoder/logits_dense/kernel'''].T return new def a ( snake_case__: List[str] , snake_case__: bool ): '''simple docstring''' lowercase_ = 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: lowercase_ = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: lowercase_ = 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.''' ) lowercase_ = state_dict['''shared.weight'''] return state_dict def a ( snake_case__: Optional[int] , snake_case__: int , snake_case__: int , snake_case__: int , snake_case__: Union[str, Any] ): '''simple docstring''' lowercase_ = checkpoints.load_tax_checkpoint(snake_case__ ) lowercase_ = convert_tax_to_pytorch( snake_case__ , num_layers=config.num_layers , is_encoder_only=snake_case__ , scalable_attention=snake_case__ ) lowercase_ = make_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ , strict=snake_case__ ) def a ( snake_case__: Optional[int] , snake_case__: List[Any] , snake_case__: Optional[int] , snake_case__: bool = False , snake_case__: bool = False , ): '''simple docstring''' lowercase_ = MTaConfig.from_json_file(snake_case__ ) 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: lowercase_ = UMTaEncoderModel(snake_case__ ) else: lowercase_ = UMTaForConditionalGeneration(snake_case__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(snake_case__ ) # Verify that we can load the checkpoint. model.from_pretrained(snake_case__ ) print('''Done''' ) if __name__ == "__main__": __a = 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 ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) __a = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
97
'''simple docstring''' import functools def a_ ( _UpperCAmelCase : list[int] ,_UpperCAmelCase : list[int] ) -> int: # Validation if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not all(isinstance(_UpperCAmelCase ,_UpperCAmelCase ) for day in days ): raise ValueError('The parameter days should be a list of integers' ) if len(_UpperCAmelCase ) != 3 or not all(isinstance(_UpperCAmelCase ,_UpperCAmelCase ) for cost in costs ): raise ValueError('The parameter costs should be a list of three integers' ) if len(_UpperCAmelCase ) == 0: return 0 if min(_UpperCAmelCase ) <= 0: raise ValueError('All days elements should be greater than 0' ) if max(_UpperCAmelCase ) >= 3_66: raise ValueError('All days elements should be less than 366' ) __snake_case : str = set(_UpperCAmelCase ) @functools.cache def dynamic_programming(_UpperCAmelCase : int ) -> int: if index > 3_65: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) ,costs[1] + dynamic_programming(index + 7 ) ,costs[2] + dynamic_programming(index + 30 ) ,) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
286
0
import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : """simple docstring""" def __init__( self : str , _snake_case : Union[str, Any] , _snake_case : Dict=14 , _snake_case : Optional[int]=7 , _snake_case : Tuple=True , _snake_case : Union[str, Any]=True , _snake_case : Any=True , _snake_case : str=True , _snake_case : Optional[int]=True , _snake_case : Any=99 , _snake_case : Optional[Any]=32 , _snake_case : Union[str, Any]=5 , _snake_case : Any=4 , _snake_case : Optional[Any]=37 , _snake_case : str="gelu" , _snake_case : Union[str, Any]=0.1 , _snake_case : Tuple=0.1 , _snake_case : Dict=512 , _snake_case : Union[str, Any]=16 , _snake_case : Any=2 , _snake_case : Dict=0.02 , _snake_case : List[Any]=3 , _snake_case : Any=4 , _snake_case : List[Any]=None , ): __lowercase : str = parent __lowercase : List[Any] = batch_size __lowercase : Optional[Any] = seq_length __lowercase : Any = is_training __lowercase : int = use_token_type_ids __lowercase : Optional[int] = use_input_mask __lowercase : Optional[Any] = use_labels __lowercase : Any = use_mc_token_ids __lowercase : Optional[Any] = vocab_size __lowercase : str = hidden_size __lowercase : Tuple = num_hidden_layers __lowercase : Optional[Any] = num_attention_heads __lowercase : Tuple = intermediate_size __lowercase : Union[str, Any] = hidden_act __lowercase : Optional[Any] = hidden_dropout_prob __lowercase : Dict = attention_probs_dropout_prob __lowercase : Optional[Any] = max_position_embeddings __lowercase : int = type_vocab_size __lowercase : int = type_sequence_label_size __lowercase : List[str] = initializer_range __lowercase : Optional[int] = num_labels __lowercase : Optional[Any] = num_choices __lowercase : Optional[Any] = scope __lowercase : Dict = self.vocab_size - 1 def snake_case_ ( self : Optional[Any] ): __lowercase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase : Optional[int] = None if self.use_input_mask: __lowercase : int = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase : int = None if self.use_token_type_ids: __lowercase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowercase : Any = None if self.use_mc_token_ids: __lowercase : Dict = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __lowercase : Any = None __lowercase : Optional[Any] = None __lowercase : Union[str, Any] = None if self.use_labels: __lowercase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) __lowercase : Any = self.get_config() __lowercase : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def snake_case_ ( self : str ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def snake_case_ ( self : Tuple , _snake_case : Union[str, Any] , _snake_case : Optional[int] , _snake_case : List[str] , _snake_case : Tuple , _snake_case : Any , *_snake_case : Dict ): __lowercase : List[Any] = CTRLModel(config=_snake_case ) model.to(_snake_case ) model.eval() model(_snake_case , token_type_ids=_snake_case , head_mask=_snake_case ) model(_snake_case , token_type_ids=_snake_case ) __lowercase : List[str] = model(_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def snake_case_ ( self : List[Any] , _snake_case : int , _snake_case : Union[str, Any] , _snake_case : Union[str, Any] , _snake_case : int , _snake_case : Dict , *_snake_case : Optional[Any] ): __lowercase : Dict = CTRLLMHeadModel(_snake_case ) model.to(_snake_case ) model.eval() __lowercase : Optional[Any] = model(_snake_case , token_type_ids=_snake_case , labels=_snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_ ( self : List[str] ): __lowercase : List[Any] = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) : Tuple = config_and_inputs __lowercase : List[str] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def snake_case_ ( self : Dict , _snake_case : int , _snake_case : List[str] , _snake_case : Any , _snake_case : str , *_snake_case : List[Any] ): __lowercase : List[Any] = self.num_labels __lowercase : str = CTRLForSequenceClassification(_snake_case ) model.to(_snake_case ) model.eval() __lowercase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase : int = model(_snake_case , token_type_ids=_snake_case , labels=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" A__ : Optional[Any] = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () A__ : int = (CTRLLMHeadModel,) if is_torch_available() else () A__ : Dict = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) A__ : str = True A__ : Optional[Any] = False A__ : Dict = False def snake_case_ ( self : str , _snake_case : Tuple , _snake_case : Any , _snake_case : Optional[Any] , _snake_case : Optional[Any] , _snake_case : Union[str, Any] ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def snake_case_ ( self : List[Any] ): __lowercase : Optional[Any] = CTRLModelTester(self ) __lowercase : Union[str, Any] = ConfigTester(self , config_class=_snake_case , n_embd=37 ) def snake_case_ ( self : Dict ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def snake_case_ ( self : Dict ): self.config_tester.run_common_tests() def snake_case_ ( self : Any ): __lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_snake_case ) def snake_case_ ( self : Any ): __lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_snake_case ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def snake_case_ ( self : Dict ): pass @slow def snake_case_ ( self : int ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase : Optional[int] = CTRLModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def snake_case_ ( self : Union[str, Any] ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self : Tuple ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def snake_case_ ( self : List[str] ): __lowercase : List[str] = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_snake_case ) __lowercase : Optional[int] = torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=_snake_case ) # Legal the president is __lowercase : Optional[int] = [ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __lowercase : List[str] = model.generate(_snake_case , do_sample=_snake_case ) self.assertListEqual(output_ids[0].tolist() , _snake_case )
284
def UpperCAmelCase_ ( __lowerCAmelCase ) -> int: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('''multiplicative_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''multiplicative_persistence() does not accept negative values''' ) __lowercase : Dict = 0 __lowercase : Optional[int] = str(__lowerCAmelCase ) while len(__lowerCAmelCase ) != 1: __lowercase : str = [int(__lowerCAmelCase ) for i in num_string] __lowercase : Union[str, Any] = 1 for i in range(0 , len(__lowerCAmelCase ) ): total *= numbers[i] __lowercase : Any = str(__lowerCAmelCase ) steps += 1 return steps def UpperCAmelCase_ ( __lowerCAmelCase ) -> int: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('''additive_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''additive_persistence() does not accept negative values''' ) __lowercase : Any = 0 __lowercase : Union[str, Any] = str(__lowerCAmelCase ) while len(__lowerCAmelCase ) != 1: __lowercase : List[str] = [int(__lowerCAmelCase ) for i in num_string] __lowercase : Tuple = 0 for i in range(0 , len(__lowerCAmelCase ) ): total += numbers[i] __lowercase : List[str] = str(__lowerCAmelCase ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
284
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCAmelCase = { 'configuration_mvp': ['MVP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MvpConfig', 'MvpOnnxConfig'], 'tokenization_mvp': ['MvpTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ['MvpTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ 'MVP_PRETRAINED_MODEL_ARCHIVE_LIST', 'MvpForCausalLM', 'MvpForConditionalGeneration', 'MvpForQuestionAnswering', 'MvpForSequenceClassification', 'MvpModel', 'MvpPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
161
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Dict = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[int] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
365
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging A = logging.get_logger(__name__) A = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' lowerCAmelCase_ = 'sew' def __init__( self : str , snake_case__ : Optional[int]=3_2 , snake_case__ : Optional[int]=7_6_8 , snake_case__ : List[Any]=1_2 , snake_case__ : List[Any]=1_2 , snake_case__ : Union[str, Any]=3_0_7_2 , snake_case__ : Union[str, Any]=2 , snake_case__ : str="gelu" , snake_case__ : Tuple=0.1 , snake_case__ : int=0.1 , snake_case__ : List[str]=0.1 , snake_case__ : Any=0.0 , snake_case__ : Dict=0.1 , snake_case__ : Any=0.1 , snake_case__ : Optional[Any]=0.02 , snake_case__ : Optional[int]=1e-5 , snake_case__ : Optional[Any]="group" , snake_case__ : Dict="gelu" , snake_case__ : str=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , snake_case__ : Union[str, Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , snake_case__ : List[Any]=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , snake_case__ : Optional[Any]=False , snake_case__ : int=1_2_8 , snake_case__ : Union[str, Any]=1_6 , snake_case__ : str=True , snake_case__ : int=0.05 , snake_case__ : Tuple=1_0 , snake_case__ : int=2 , snake_case__ : str=0.0 , snake_case__ : Tuple=1_0 , snake_case__ : List[str]=0 , snake_case__ : Any="mean" , snake_case__ : Optional[Any]=False , snake_case__ : str=False , snake_case__ : str=2_5_6 , snake_case__ : str=0 , snake_case__ : List[Any]=1 , snake_case__ : Dict=2 , **snake_case__ : Optional[int] , ) -> Tuple: super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) _lowerCamelCase = hidden_size _lowerCamelCase = feat_extract_norm _lowerCamelCase = feat_extract_activation _lowerCamelCase = list(snake_case__ ) _lowerCamelCase = list(snake_case__ ) _lowerCamelCase = list(snake_case__ ) _lowerCamelCase = conv_bias _lowerCamelCase = num_conv_pos_embeddings _lowerCamelCase = num_conv_pos_embedding_groups _lowerCamelCase = len(self.conv_dim ) _lowerCamelCase = num_hidden_layers _lowerCamelCase = intermediate_size _lowerCamelCase = squeeze_factor _lowerCamelCase = hidden_act _lowerCamelCase = num_attention_heads _lowerCamelCase = hidden_dropout _lowerCamelCase = attention_dropout _lowerCamelCase = activation_dropout _lowerCamelCase = feat_proj_dropout _lowerCamelCase = final_dropout _lowerCamelCase = layerdrop _lowerCamelCase = layer_norm_eps _lowerCamelCase = initializer_range _lowerCamelCase = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f"""but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _lowerCamelCase = apply_spec_augment _lowerCamelCase = mask_time_prob _lowerCamelCase = mask_time_length _lowerCamelCase = mask_time_min_masks _lowerCamelCase = mask_feature_prob _lowerCamelCase = mask_feature_length _lowerCamelCase = mask_feature_min_masks # ctc loss _lowerCamelCase = ctc_loss_reduction _lowerCamelCase = ctc_zero_infinity # sequence classification _lowerCamelCase = use_weighted_layer_sum _lowerCamelCase = classifier_proj_size @property def _snake_case ( self : int ) -> List[str]: return functools.reduce(operator.mul , self.conv_stride , 1 )
234
import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[Any] , snake_case__ : int , snake_case__ : Optional[Any]=1_3 , snake_case__ : Tuple=7 , snake_case__ : Any=True , snake_case__ : Any=True , snake_case__ : Optional[Any]=False , snake_case__ : Optional[Any]=True , snake_case__ : List[str]=9_9 , snake_case__ : Optional[int]=6_4 , snake_case__ : Dict=5 , snake_case__ : Dict=4 , snake_case__ : Union[str, Any]=6_4 , snake_case__ : Dict="gelu" , snake_case__ : Optional[int]=0.1 , snake_case__ : Optional[Any]=0.1 , snake_case__ : List[Any]=5_1_2 , snake_case__ : Any=1_6 , snake_case__ : List[str]=2 , snake_case__ : Dict=0.02 , snake_case__ : Tuple=3 , snake_case__ : Optional[int]=4 , snake_case__ : Optional[int]=None , ) -> Optional[int]: _lowerCamelCase = parent _lowerCamelCase = batch_size _lowerCamelCase = seq_length _lowerCamelCase = is_training _lowerCamelCase = use_input_mask _lowerCamelCase = use_token_type_ids _lowerCamelCase = use_labels _lowerCamelCase = vocab_size _lowerCamelCase = hidden_size _lowerCamelCase = num_hidden_layers _lowerCamelCase = num_attention_heads _lowerCamelCase = intermediate_size _lowerCamelCase = hidden_act _lowerCamelCase = hidden_dropout_prob _lowerCamelCase = attention_probs_dropout_prob _lowerCamelCase = max_position_embeddings _lowerCamelCase = type_vocab_size _lowerCamelCase = type_sequence_label_size _lowerCamelCase = initializer_range _lowerCamelCase = num_labels _lowerCamelCase = num_choices _lowerCamelCase = scope def _snake_case ( self : Tuple ) -> Union[str, Any]: return MPNetConfig.from_pretrained('microsoft/mpnet-base' ) def _snake_case ( self : List[str] ) -> str: _lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase = None if self.use_input_mask: _lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase = None _lowerCamelCase = None _lowerCamelCase = None if self.use_labels: _lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self : Union[str, Any] ) -> int: return MPNetConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def _snake_case ( self : str , snake_case__ : List[Any] , snake_case__ : Dict , snake_case__ : int , snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : Dict ) -> Dict: _lowerCamelCase = MPNetModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model(snake_case__ , snake_case__ ) _lowerCamelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[int] , snake_case__ : str , snake_case__ : str , snake_case__ : Tuple , snake_case__ : Union[str, Any] ) -> List[str]: _lowerCamelCase = MPNetForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model( snake_case__ , attention_mask=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self : Optional[int] , snake_case__ : Tuple , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : Optional[Any] , snake_case__ : Dict , snake_case__ : List[str] ) -> List[str]: _lowerCamelCase = self.num_labels _lowerCamelCase = MPNetForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Optional[int] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : int , snake_case__ : Optional[int] ) -> Any: _lowerCamelCase = self.num_choices _lowerCamelCase = MPNetForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase = model( snake_case__ , attention_mask=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self : str , snake_case__ : Any , snake_case__ : Dict , snake_case__ : str , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : str ) -> Optional[int]: _lowerCamelCase = self.num_labels _lowerCamelCase = MPNetForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self : int ) -> Any: _lowerCamelCase = self.prepare_config_and_inputs() ((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = config_and_inputs _lowerCamelCase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) lowerCAmelCase_ = ( { 'feature-extraction': MPNetModel, 'fill-mask': MPNetForMaskedLM, 'question-answering': MPNetForQuestionAnswering, 'text-classification': MPNetForSequenceClassification, 'token-classification': MPNetForTokenClassification, 'zero-shot': MPNetForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = True def _snake_case ( self : Any ) -> List[Any]: _lowerCamelCase = MPNetModelTester(self ) _lowerCamelCase = ConfigTester(self , config_class=snake_case__ , hidden_size=3_7 ) def _snake_case ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def _snake_case ( self : Tuple ) -> List[Any]: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*snake_case__ ) def _snake_case ( self : List[Any] ) -> Optional[int]: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*snake_case__ ) def _snake_case ( self : Optional[int] ) -> List[Any]: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*snake_case__ ) def _snake_case ( self : Tuple ) -> Union[str, Any]: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*snake_case__ ) def _snake_case ( self : Dict ) -> Dict: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*snake_case__ ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : Tuple ) -> Optional[Any]: _lowerCamelCase = MPNetModel.from_pretrained('microsoft/mpnet-base' ) _lowerCamelCase = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase = model(snake_case__ )[0] _lowerCamelCase = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , snake_case__ ) _lowerCamelCase = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) )
234
1
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = (EulerDiscreteScheduler,) __UpperCAmelCase : Union[str, Any] = 1_0 def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def __UpperCAmelCase ( self ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma __a = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): __a = scheduler.scale_model_input(_a , _a ) __a = model(_a , _a ) __a = scheduler.step(_a , _a , _a , generator=_a ) __a = output.prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(prediction_type='''v_prediction''' ) __a = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma __a = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): __a = scheduler.scale_model_input(_a , _a ) __a = model(_a , _a ) __a = scheduler.step(_a , _a , _a , generator=_a ) __a = output.prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 0.0002 ) < 1E-2 assert abs(result_mean.item() - 2.2_676E-06 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __a = sample.to(_a ) for t in scheduler.timesteps: __a = scheduler.scale_model_input(_a , _a ) __a = model(_a , _a ) __a = scheduler.step(_a , _a , _a , generator=_a ) __a = output.prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a , use_karras_sigmas=_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __a = sample.to(_a ) for t in scheduler.timesteps: __a = scheduler.scale_model_input(_a , _a ) __a = model(_a , _a ) __a = scheduler.step(_a , _a , _a , generator=_a ) __a = output.prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 124.52_2994_9951_1719 ) < 1E-2 assert abs(result_mean.item() - 0.1_6213_9326_3339_9963 ) < 1E-3
695
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( lowerCAmelCase__ : float = 0.1 ) -> int: __a = 3 __a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowerCAmelCase__ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
695
1
# 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 warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __A( UpperCAmelCase ): def __init__( self : Dict , __UpperCamelCase : int ): lowerCamelCase_ = data def __iter__( self : Optional[Any] ): for element in self.data: yield element def __lowerCAmelCase ( UpperCAmelCase__ : List[str]=True ) -> Tuple: lowerCamelCase_ = Accelerator(even_batches=UpperCAmelCase__ ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def __lowerCAmelCase ( UpperCAmelCase__ : Accelerator , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : bool = False ) -> Union[str, Any]: if iterable: lowerCamelCase_ = DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) else: lowerCamelCase_ = TensorDataset(torch.as_tensor(range(UpperCAmelCase__ ) ) ) lowerCamelCase_ = DataLoader(UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) lowerCamelCase_ = accelerator.prepare(UpperCAmelCase__ ) return dl def __lowerCAmelCase ( UpperCAmelCase__ : Accelerator , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : List[int] , ) -> int: lowerCamelCase_ = create_dataloader(accelerator=UpperCAmelCase__ , dataset_size=UpperCAmelCase__ , batch_size=UpperCAmelCase__ ) lowerCamelCase_ = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def __lowerCAmelCase ( ) -> List[str]: lowerCamelCase_ = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def __lowerCAmelCase ( ) -> List[str]: lowerCamelCase_ = create_accelerator(even_batches=UpperCAmelCase__ ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( UpperCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def __lowerCAmelCase ( ) -> Tuple: lowerCamelCase_ = create_accelerator(even_batches=UpperCAmelCase__ ) lowerCamelCase_ = torch.nn.Linear(1 , 1 ) lowerCamelCase_ = accelerator.prepare(UpperCAmelCase__ ) lowerCamelCase_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) lowerCamelCase_ = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(UpperCAmelCase__ ): lowerCamelCase_ = ddp_model(batch[0].float() ) lowerCamelCase_ = output.sum() loss.backward() batch_idxs.append(UpperCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def __lowerCAmelCase ( UpperCAmelCase__ : Tuple ) -> List[Any]: with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for multi-GPU" in str(w[-1].message ) def __lowerCAmelCase ( ) -> Optional[Any]: lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = create_accelerator(even_batches=UpperCAmelCase__ ) lowerCamelCase_ = torch.nn.Linear(1 , 1 ) lowerCamelCase_ = accelerator.prepare(UpperCAmelCase__ ) lowerCamelCase_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) lowerCamelCase_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): lowerCamelCase_ = train_dl.batch_sampler.even_batches lowerCamelCase_ = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def __lowerCAmelCase ( ) -> Optional[Any]: lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = create_accelerator(even_batches=UpperCAmelCase__ ) lowerCamelCase_ = torch.nn.Linear(1 , 1 ) lowerCamelCase_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) lowerCamelCase_ = create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): lowerCamelCase_ = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def __lowerCAmelCase ( ) -> str: lowerCamelCase_ = create_accelerator() lowerCamelCase_ = torch.nn.Linear(1 , 1 ) lowerCamelCase_ = accelerator.prepare(UpperCAmelCase__ ) create_dataloader(UpperCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=UpperCAmelCase__ ) with warnings.catch_warnings(record=UpperCAmelCase__ ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=UpperCAmelCase__ ): pass assert issubclass(w[-1].category , UpperCAmelCase__ ) assert "only supported for map-style datasets" in str(w[-1].message ) def __lowerCAmelCase ( ) -> Union[str, Any]: lowerCamelCase_ = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) lowerCamelCase_ = accelerator.state.distributed_type lowerCamelCase_ = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase__ ) lowerCamelCase_ = original_state if __name__ == "__main__": main()
103
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer lowercase = logging.get_logger(__name__) lowercase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowercase = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } lowercase = {'''mobilebert-uncased''': 5_1_2} lowercase = {} class __A( UpperCAmelCase ): SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE = MobileBertTokenizer def __init__( self : Union[str, Any] , __UpperCamelCase : str=None , __UpperCamelCase : str=None , __UpperCamelCase : Dict=True , __UpperCamelCase : Any="[UNK]" , __UpperCamelCase : str="[SEP]" , __UpperCamelCase : Dict="[PAD]" , __UpperCamelCase : List[str]="[CLS]" , __UpperCamelCase : Any="[MASK]" , __UpperCamelCase : Any=True , __UpperCamelCase : int=None , **__UpperCamelCase : Dict , ): super().__init__( __UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , tokenize_chinese_chars=__UpperCamelCase , strip_accents=__UpperCamelCase , **__UpperCamelCase , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCamelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCamelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCamelCase ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(__UpperCamelCase , normalizer_state.pop("""type""" ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**__UpperCamelCase ) lowerCamelCase_ = do_lower_case def lowercase__ ( self : List[str] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict=None ): lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowercase__ ( self : Tuple , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None ): lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowercase__ ( self : List[str] , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None ): lowerCamelCase_ = self._tokenizer.model.save(__UpperCamelCase , name=__UpperCamelCase ) return tuple(__UpperCamelCase )
103
1
"""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, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' UpperCamelCase = StableDiffusionInstructPixaPixPipeline UpperCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase__ ( self : List[str] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) UpperCAmelCase_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) torch.manual_seed(0 ) UpperCAmelCase_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCAmelCase_ = 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=1000 , ) UpperCAmelCase_ = CLIPTextModel(_UpperCAmelCase ) UpperCAmelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) UpperCAmelCase_ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowercase__ ( self : Optional[int] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Dict=0 ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) UpperCAmelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase_ = Image.fromarray(np.uinta(_UpperCAmelCase ) ).convert("RGB" ) if str(_UpperCAmelCase ).startswith("mps" ): UpperCAmelCase_ = torch.manual_seed(_UpperCAmelCase ) else: UpperCAmelCase_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) UpperCAmelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "image_guidance_scale": 1, "output_type": "numpy", } return inputs def lowercase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCAmelCase_ = self.get_dummy_inputs(_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCAmelCase_ = self.get_dummy_inputs(_UpperCAmelCase ) UpperCAmelCase_ = "french fries" UpperCAmelCase_ = sd_pipe(**_UpperCAmelCase , negative_prompt=_UpperCAmelCase ) UpperCAmelCase_ = output.images UpperCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : Tuple ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCAmelCase_ = self.get_dummy_inputs(_UpperCAmelCase ) UpperCAmelCase_ = [inputs["prompt"]] * 2 UpperCAmelCase_ = np.array(inputs["image"] ).astype(np.floataa ) / 255.0 UpperCAmelCase_ = torch.from_numpy(_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) UpperCAmelCase_ = image / 2 + 0.5 UpperCAmelCase_ = image.permute(0 , 3 , 1 , 2 ) UpperCAmelCase_ = image.repeat(2 , 1 , 1 , 1 ) UpperCAmelCase_ = sd_pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) UpperCAmelCase_ = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : str ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="scaled_linear" ) UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCAmelCase_ = self.get_dummy_inputs(_UpperCAmelCase ) UpperCAmelCase_ = sd_pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = [round(_UpperCAmelCase , 4 ) for x in image_slice.flatten().tolist()] print(",".join([str(_UpperCAmelCase ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowercase__ ( self : int ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) UpperCAmelCase_ = VaeImageProcessor(do_resize=_UpperCAmelCase , do_normalize=_UpperCAmelCase ) UpperCAmelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCAmelCase_ = pipe(**self.get_dummy_inputs_by_type(_UpperCAmelCase , input_image_type="pt" ) )[0] UpperCAmelCase_ = components["vae"] UpperCAmelCase_ = self.get_dummy_inputs_by_type(_UpperCAmelCase , input_image_type="pt" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): UpperCAmelCase_ = vae.encode(inputs[image_param] ).latent_dist.mode() UpperCAmelCase_ = pipe(**_UpperCAmelCase )[0] UpperCAmelCase_ = np.abs(out - out_latents_inputs ).max() self.assertLess(_UpperCAmelCase , 1e-4 , "passing latents as image input generate different result from passing image" ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): '''simple docstring''' def lowercase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : Optional[int] , _UpperCAmelCase : Optional[int]=0 ) -> int: '''simple docstring''' UpperCAmelCase_ = torch.manual_seed(_UpperCAmelCase ) UpperCAmelCase_ = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg" ) UpperCAmelCase_ = { "prompt": "turn him into a cyborg", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "image_guidance_scale": 1.0, "output_type": "numpy", } return inputs def lowercase__ ( self : str ) -> str: '''simple docstring''' UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() UpperCAmelCase_ = self.get_inputs() UpperCAmelCase_ = pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase_ = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=_UpperCAmelCase ) UpperCAmelCase_ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() UpperCAmelCase_ = self.get_inputs() UpperCAmelCase_ = pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase_ = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=_UpperCAmelCase ) UpperCAmelCase_ = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() UpperCAmelCase_ = self.get_inputs() UpperCAmelCase_ = pipe(**_UpperCAmelCase ).images UpperCAmelCase_ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase_ = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : Any ) -> str: '''simple docstring''' UpperCAmelCase_ = 0 def callback_fn(_UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : torch.FloatTensor ) -> None: UpperCAmelCase_ = True nonlocal number_of_steps number_of_steps += 1 if step == 1: UpperCAmelCase_ = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) UpperCAmelCase_ = latents[0, -3:, -3:, -1] UpperCAmelCase_ = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: UpperCAmelCase_ = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) UpperCAmelCase_ = latents[0, -3:, -3:, -1] UpperCAmelCase_ = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 UpperCAmelCase_ = False UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=_UpperCAmelCase , torch_dtype=torch.floataa ) UpperCAmelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() UpperCAmelCase_ = self.get_inputs() pipe(**_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowercase__ ( self : Tuple ) -> Dict: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix" , safety_checker=_UpperCAmelCase , torch_dtype=torch.floataa ) UpperCAmelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCAmelCase_ = self.get_inputs() UpperCAmelCase_ = pipe(**_UpperCAmelCase ) UpperCAmelCase_ = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowercase__ ( self : Tuple ) -> Any: '''simple docstring''' UpperCAmelCase_ = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 UpperCAmelCase_ = inputs["image"].resize((504, 504) ) UpperCAmelCase_ = "timbrooks/instruct-pix2pix" UpperCAmelCase_ = StableDiffusionInstructPixaPixPipeline.from_pretrained( _UpperCAmelCase , safety_checker=_UpperCAmelCase , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() UpperCAmelCase_ = pipe(**_UpperCAmelCase ) UpperCAmelCase_ = output.images[0] UpperCAmelCase_ = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) UpperCAmelCase_ = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
82
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative" ) elif capacitance <= 0: raise ValueError("Capacitance cannot be 0 or negative" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
82
1
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCAmelCase__ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def a__ ( SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def a__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' if args.student_type == "roberta": lowerCAmelCase : Optional[int] = False elif args.student_type == "gpt2": lowerCAmelCase : Union[str, Any] = False def a__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' if args.student_type == "roberta": lowerCAmelCase : Any = False def a__ ( ): '''simple docstring''' lowerCAmelCase : Optional[int] = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=SCREAMING_SNAKE_CASE , choices=["distilbert", "roberta", "gpt2"] , required=SCREAMING_SNAKE_CASE , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=SCREAMING_SNAKE_CASE , type=SCREAMING_SNAKE_CASE , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=SCREAMING_SNAKE_CASE , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=SCREAMING_SNAKE_CASE , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=SCREAMING_SNAKE_CASE , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=SCREAMING_SNAKE_CASE , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=SCREAMING_SNAKE_CASE , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=SCREAMING_SNAKE_CASE , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=SCREAMING_SNAKE_CASE , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=SCREAMING_SNAKE_CASE , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=SCREAMING_SNAKE_CASE , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=SCREAMING_SNAKE_CASE , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=SCREAMING_SNAKE_CASE , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=SCREAMING_SNAKE_CASE , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=SCREAMING_SNAKE_CASE , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=SCREAMING_SNAKE_CASE , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=SCREAMING_SNAKE_CASE , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=SCREAMING_SNAKE_CASE , default=5_0 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=SCREAMING_SNAKE_CASE , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=SCREAMING_SNAKE_CASE , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=SCREAMING_SNAKE_CASE , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=SCREAMING_SNAKE_CASE , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=SCREAMING_SNAKE_CASE , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=SCREAMING_SNAKE_CASE , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=SCREAMING_SNAKE_CASE , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=SCREAMING_SNAKE_CASE , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=SCREAMING_SNAKE_CASE , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=SCREAMING_SNAKE_CASE , default=5_6 , help="Random seed" ) parser.add_argument("--log_interval" , type=SCREAMING_SNAKE_CASE , default=5_0_0 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=SCREAMING_SNAKE_CASE , default=4_0_0_0 , help="Checkpoint interval." ) lowerCAmelCase : List[str] = parser.parse_args() sanity_checks(SCREAMING_SNAKE_CASE ) # ARGS # init_gpu_params(SCREAMING_SNAKE_CASE ) set_seed(SCREAMING_SNAKE_CASE ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , indent=4 ) git_log(args.dump_path ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[Any] = MODEL_CLASSES[args.student_type] lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Tuple = MODEL_CLASSES[args.teacher_type] # TOKENIZER # lowerCAmelCase : List[Any] = teacher_tokenizer_class.from_pretrained(args.teacher_name ) lowerCAmelCase : Union[str, Any] = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): lowerCAmelCase : Optional[Any] = tokenizer.all_special_tokens.index(SCREAMING_SNAKE_CASE ) lowerCAmelCase : List[str] = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) lowerCAmelCase : List[Any] = special_tok_ids lowerCAmelCase : List[str] = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: lowerCAmelCase : List[Any] = pickle.load(SCREAMING_SNAKE_CASE ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: lowerCAmelCase : List[str] = pickle.load(SCREAMING_SNAKE_CASE ) lowerCAmelCase : Optional[int] = np.maximum(SCREAMING_SNAKE_CASE , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): lowerCAmelCase : Tuple = 0.0 # do not predict special tokens lowerCAmelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE ) else: lowerCAmelCase : Union[str, Any] = None lowerCAmelCase : Union[str, Any] = LmSeqsDataset(params=SCREAMING_SNAKE_CASE , data=SCREAMING_SNAKE_CASE ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) lowerCAmelCase : Optional[Any] = student_config_class.from_pretrained(args.student_config ) lowerCAmelCase : str = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) lowerCAmelCase : List[str] = student_model_class.from_pretrained(args.student_pretrained_weights , config=SCREAMING_SNAKE_CASE ) else: lowerCAmelCase : int = student_model_class(SCREAMING_SNAKE_CASE ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # lowerCAmelCase : Any = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=SCREAMING_SNAKE_CASE ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if args.freeze_token_type_embds: freeze_token_type_embeddings(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() lowerCAmelCase : Tuple = Distiller( params=SCREAMING_SNAKE_CASE , dataset=SCREAMING_SNAKE_CASE , token_probs=SCREAMING_SNAKE_CASE , student=SCREAMING_SNAKE_CASE , teacher=SCREAMING_SNAKE_CASE ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
681
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__=3 , snake_case__=32 , snake_case__=3 , snake_case__=10 , snake_case__=[10, 20, 30, 40] , snake_case__=[1, 1, 2, 1] , snake_case__=True , snake_case__=True , snake_case__="relu" , snake_case__=3 , snake_case__=None , ): """simple docstring""" lowerCAmelCase : Optional[Any] = parent lowerCAmelCase : List[Any] = batch_size lowerCAmelCase : Union[str, Any] = image_size lowerCAmelCase : Dict = num_channels lowerCAmelCase : List[Any] = embeddings_size lowerCAmelCase : List[Any] = hidden_sizes lowerCAmelCase : Optional[int] = depths lowerCAmelCase : str = is_training lowerCAmelCase : List[str] = use_labels lowerCAmelCase : List[Any] = hidden_act lowerCAmelCase : Optional[Any] = num_labels lowerCAmelCase : Tuple = scope lowerCAmelCase : int = len(snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase : Optional[Any] = None if self.use_labels: lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase : List[str] = self.get_config() return config, pixel_values, labels def lowercase__ ( self ): """simple docstring""" return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Tuple = TFResNetModel(config=snake_case__ ) lowerCAmelCase : Union[str, Any] = model(snake_case__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Dict = self.num_labels lowerCAmelCase : str = TFResNetForImageClassification(snake_case__ ) lowerCAmelCase : int = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Any = config_and_inputs lowerCAmelCase : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( lowercase , lowercase , unittest.TestCase ): """simple docstring""" a : Any =(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () a : Tuple =( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) a : int =False a : List[str] =False a : Optional[int] =False a : Union[str, Any] =False a : Any =False def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[Any] = TFResNetModelTester(self ) lowerCAmelCase : str = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ ) def lowercase__ ( self ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase__ ( self ): """simple docstring""" return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def lowercase__ ( self ): """simple docstring""" pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" lowerCAmelCase , lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : List[str] = model_class(snake_case__ ) lowerCAmelCase : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase : Dict = [*signature.parameters.keys()] lowerCAmelCase : List[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def lowercase__ ( self ): """simple docstring""" def check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ): lowerCAmelCase : int = model_class(snake_case__ ) lowerCAmelCase : Optional[Any] = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) lowerCAmelCase : List[str] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase : Tuple = self.model_tester.num_stages self.assertEqual(len(snake_case__ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCAmelCase , lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Any = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCAmelCase : Optional[Any] = layer_type lowerCAmelCase : Dict = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase : List[Any] = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def lowercase__ ( self ): """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase : int = TFResNetModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def a__ ( ): '''simple docstring''' lowerCAmelCase : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowercase__ ( self ): """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : int = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCAmelCase : Any = self.default_image_processor lowerCAmelCase : Optional[Any] = prepare_img() lowerCAmelCase : Dict = image_processor(images=snake_case__ , return_tensors="tf" ) # forward pass lowerCAmelCase : str = model(**snake_case__ ) # verify the logits lowerCAmelCase : str = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , snake_case__ ) lowerCAmelCase : str = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , snake_case__ , atol=1e-4 ) )
681
1
import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class UpperCAmelCase__ ( unittest.TestCase ): def A__ ( self ): _A : List[Any] = inspect.getfile(accelerate.test_utils ) _A : Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) _A : Any = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def A__ ( self ): _A : Union[str, Any] = f"""\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n """.split() _A : List[str] = [sys.executable] + distributed_args execute_subprocess_async(A__ ,env=os.environ.copy() )
206
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = 42 UpperCamelCase__ = 42 def __init__( self :Any , __magic_name__ :UNetaDModel , __magic_name__ :ScoreSdeVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=__magic_name__ , scheduler=__magic_name__ ) @torch.no_grad() def __call__( self :List[str] , __magic_name__ :int = 1 , __magic_name__ :int = 2000 , __magic_name__ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __magic_name__ :Optional[str] = "pil" , __magic_name__ :bool = True , **__magic_name__ :Union[str, Any] , ): '''simple docstring''' a = self.unet.config.sample_size a = (batch_size, 3, img_size, img_size) a = self.unet a = randn_tensor(__magic_name__ , generator=__magic_name__ ) * self.scheduler.init_noise_sigma a = sample.to(self.device ) self.scheduler.set_timesteps(__magic_name__ ) self.scheduler.set_sigmas(__magic_name__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): a = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): a = self.unet(__magic_name__ , __magic_name__ ).sample a = self.scheduler.step_correct(__magic_name__ , __magic_name__ , generator=__magic_name__ ).prev_sample # prediction step a = model(__magic_name__ , __magic_name__ ).sample a = self.scheduler.step_pred(__magic_name__ , __magic_name__ , __magic_name__ , generator=__magic_name__ ) a , a = output.prev_sample, output.prev_sample_mean a = sample_mean.clamp(0 , 1 ) a = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a = self.numpy_to_pil(__magic_name__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=__magic_name__ )
468
0
from abc import ABC, abstractmethod from typing import List, Optional class a__ ( lowercase__ ): """simple docstring""" def __init__( self :Optional[int] ): self.test() def __UpperCAmelCase ( self :Any ): lowercase = 0 lowercase = False while not completed: if counter == 1: self.reset() lowercase = self.advance() if not self.does_advance(__lowerCamelCase ): raise Exception( 'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' ) lowercase = self.update(__lowerCamelCase ) counter += 1 if counter > 1_0000: raise Exception('update() does not fulfill the constraint.' ) if self.remaining() != 0: raise Exception('Custom Constraint is not defined correctly.' ) @abstractmethod def __UpperCAmelCase ( self :List[Any] ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self :List[Any] , lowercase__ :int ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self :Any , lowercase__ :int ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self :List[Any] ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self :Union[str, Any] ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self :Tuple , lowercase__ :Any=False ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class a__ ( lowercase__ ): """simple docstring""" def __init__( self :Optional[int] , lowercase__ :List[int] ): super(__lowerCamelCase , self ).__init__() if not isinstance(__lowerCamelCase , __lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(__lowerCamelCase , __lowerCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(F"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) lowercase = token_ids lowercase = len(self.token_ids ) lowercase = -1 # the index of the currently fulfilled step lowercase = False def __UpperCAmelCase ( self :Tuple ): if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def __UpperCAmelCase ( self :Union[str, Any] , lowercase__ :int ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def __UpperCAmelCase ( self :List[Any] , lowercase__ :int ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) lowercase = False lowercase = False lowercase = False if self.does_advance(__lowerCamelCase ): self.fulfilled_idx += 1 lowercase = True if self.fulfilled_idx == (self.seqlen - 1): lowercase = True lowercase = completed else: # failed to make progress. lowercase = True self.reset() return stepped, completed, reset def __UpperCAmelCase ( self :int ): lowercase = False lowercase = 0 def __UpperCAmelCase ( self :List[Any] ): return self.seqlen - (self.fulfilled_idx + 1) def __UpperCAmelCase ( self :List[str] , lowercase__ :List[Any]=False ): lowercase = PhrasalConstraint(self.token_ids ) if stateful: lowercase = self.seqlen lowercase = self.fulfilled_idx lowercase = self.completed return new_constraint class a__ : """simple docstring""" def __init__( self :Optional[int] , lowercase__ :List[List[int]] , lowercase__ :Optional[int]=True ): lowercase = max([len(__lowerCamelCase ) for one in nested_token_ids] ) lowercase = {} for token_ids in nested_token_ids: lowercase = root for tidx, token_id in enumerate(__lowerCamelCase ): if token_id not in level: lowercase = {} lowercase = level[token_id] if no_subsets and self.has_subsets(__lowerCamelCase , __lowerCamelCase ): raise ValueError( 'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is' F""" {nested_token_ids}.""" ) lowercase = root def __UpperCAmelCase ( self :List[Any] , lowercase__ :Union[str, Any] ): lowercase = self.trie for current_token in current_seq: lowercase = start[current_token] lowercase = list(start.keys() ) return next_tokens def __UpperCAmelCase ( self :Dict , lowercase__ :Any ): lowercase = self.next_tokens(__lowerCamelCase ) return len(__lowerCamelCase ) == 0 def __UpperCAmelCase ( self :List[Any] , lowercase__ :int ): lowercase = list(root.values() ) if len(__lowerCamelCase ) == 0: return 1 else: return sum([self.count_leaves(__lowerCamelCase ) for nn in next_nodes] ) def __UpperCAmelCase ( self :int , lowercase__ :str , lowercase__ :str ): lowercase = self.count_leaves(__lowerCamelCase ) return len(__lowerCamelCase ) != leaf_count class a__ ( lowercase__ ): """simple docstring""" def __init__( self :str , lowercase__ :List[List[int]] ): super(__lowerCamelCase , self ).__init__() if not isinstance(__lowerCamelCase , __lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(__lowerCamelCase , __lowerCamelCase ) for token_ids in nested_token_ids ): raise ValueError(F"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(__lowerCamelCase , __lowerCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) lowercase = DisjunctiveTrie(__lowerCamelCase ) lowercase = nested_token_ids lowercase = self.trie.max_height lowercase = [] lowercase = False def __UpperCAmelCase ( self :List[Any] ): lowercase = self.trie.next_tokens(self.current_seq ) if len(__lowerCamelCase ) == 0: return None else: return token_list def __UpperCAmelCase ( self :Dict , lowercase__ :int ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) lowercase = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def __UpperCAmelCase ( self :Optional[Any] , lowercase__ :int ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) lowercase = False lowercase = False lowercase = False if self.does_advance(__lowerCamelCase ): self.current_seq.append(__lowerCamelCase ) lowercase = True else: lowercase = True self.reset() lowercase = self.trie.reached_leaf(self.current_seq ) lowercase = completed return stepped, completed, reset def __UpperCAmelCase ( self :Tuple ): lowercase = False lowercase = [] def __UpperCAmelCase ( self :int ): if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def __UpperCAmelCase ( self :Dict , lowercase__ :Dict=False ): lowercase = DisjunctiveConstraint(self.token_ids ) if stateful: lowercase = self.seqlen lowercase = self.current_seq lowercase = self.completed return new_constraint class a__ : """simple docstring""" def __init__( self :List[str] , lowercase__ :List[Constraint] ): lowercase = constraints # max # of steps required to fulfill a given constraint lowercase = max([c.seqlen for c in constraints] ) lowercase = len(__lowerCamelCase ) lowercase = False self.init_state() def __UpperCAmelCase ( self :Tuple ): lowercase = [] lowercase = None lowercase = [constraint.copy(stateful=__lowerCamelCase ) for constraint in self.constraints] def __UpperCAmelCase ( self :List[str] ): lowercase = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def __UpperCAmelCase ( self :Any ): lowercase = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowercase = constraint.advance() if isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.extend(__lowerCamelCase ) else: lowercase = self.inprogress_constraint.advance() if isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.extend(__lowerCamelCase ) if len(__lowerCamelCase ) == 0: return None else: return token_list def __UpperCAmelCase ( self :Union[str, Any] , lowercase__ :Optional[List[int]] ): self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowercase = self.add(__lowerCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def __UpperCAmelCase ( self :Any , lowercase__ :int ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" ) lowercase = False, False if self.completed: lowercase = True lowercase = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowercase = self.inprogress_constraint.update(__lowerCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCamelCase ) ) lowercase = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) lowercase = None if len(self.pending_constraints ) == 0: # we're done! lowercase = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__lowerCamelCase ): lowercase = pending_constraint.update(__lowerCamelCase ) if not stepped: raise Exception( '`constraint.update(token_id)` is not yielding incremental progress, ' 'even though `constraint.does_advance(token_id)` is true.' ) if complete: self.complete_constraints.append(__lowerCamelCase ) lowercase = None if not complete and stepped: lowercase = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowercase = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowercase = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def __UpperCAmelCase ( self :Union[str, Any] , lowercase__ :Optional[Any]=True ): lowercase = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowercase = [ constraint.copy(stateful=__lowerCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowercase = self.inprogress_constraint.copy(stateful=__lowerCamelCase ) lowercase = [constraint.copy() for constraint in self.pending_constraints] return new_state
705
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimeSeriesTransformerForPrediction''', '''TimeSeriesTransformerModel''', '''TimeSeriesTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
314
0
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _UpperCAmelCase ( a : List[Any] ): monkeypatch.setattr("""datasets.utils.deprecation_utils._emitted_deprecation_warnings""" , set() ) @pytest.fixture def _UpperCAmelCase ( a : str ): class _lowerCAmelCase : """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : Tuple): '''simple docstring''' snake_case__ = metric_id class _lowerCAmelCase : """simple docstring""" _lowercase : List[str] = [MetricMock(lowercase_ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def __magic_name__ ( self : Tuple): '''simple docstring''' return self._metrics monkeypatch.setattr("""datasets.inspect.huggingface_hub""" , HfhMock() ) @pytest.mark.parametrize( """func, args""" , [(load_metric, ("""metrics/mse""",)), (list_metrics, ()), (inspect_metric, ("""metrics/mse""", """tmp_path"""))] ) def _UpperCAmelCase ( a : Any , a : Union[str, Any] , a : List[Any] , a : Union[str, Any] , a : Tuple ): if "tmp_path" in args: snake_case__ = tuple(arg if arg != """tmp_path""" else tmp_path for arg in args ) with pytest.warns(a , match="""https://huggingface.co/docs/evaluate""" ): func(*a )
654
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property 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 TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase : """simple docstring""" _lowercase : List[str] = PegasusConfig _lowercase : Union[str, Any] = {} _lowercase : Tuple = '''gelu''' def __init__( self : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int]=1_3 , UpperCamelCase__ : Any=7 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : int=9_9 , UpperCamelCase__ : Dict=3_2 , UpperCamelCase__ : str=2 , UpperCamelCase__ : int=4 , UpperCamelCase__ : Tuple=3_7 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : str=4_0 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : Optional[Any]=1 , UpperCamelCase__ : Dict=0 , ): '''simple docstring''' snake_case__ = parent snake_case__ = batch_size snake_case__ = seq_length snake_case__ = is_training snake_case__ = use_labels snake_case__ = vocab_size snake_case__ = hidden_size snake_case__ = num_hidden_layers snake_case__ = num_attention_heads snake_case__ = intermediate_size snake_case__ = hidden_dropout_prob snake_case__ = attention_probs_dropout_prob snake_case__ = max_position_embeddings snake_case__ = eos_token_id snake_case__ = pad_token_id snake_case__ = bos_token_id def __magic_name__ ( self : Optional[Any]): '''simple docstring''' snake_case__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) snake_case__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1) snake_case__ = tf.concat([input_ids, eos_tensor] , axis=1) snake_case__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) snake_case__ = 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 , ) snake_case__ = prepare_pegasus_inputs_dict(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__) return config, inputs_dict def __magic_name__ ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any]): '''simple docstring''' snake_case__ = TFPegasusModel(config=UpperCamelCase__).get_decoder() snake_case__ = inputs_dict["""input_ids"""] snake_case__ = input_ids[:1, :] snake_case__ = inputs_dict["""attention_mask"""][:1, :] snake_case__ = inputs_dict["""head_mask"""] snake_case__ = 1 # first forward pass snake_case__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ , use_cache=UpperCamelCase__) snake_case__ , snake_case__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case__ = ids_tensor((self.batch_size, 3) , config.vocab_size) snake_case__ = tf.cast(ids_tensor((self.batch_size, 3) , 2) , tf.inta) # append to next input_ids and snake_case__ = tf.concat([input_ids, next_tokens] , axis=-1) snake_case__ = tf.concat([attention_mask, next_attn_mask] , axis=-1) snake_case__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__)[0] snake_case__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , past_key_values=UpperCamelCase__)[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1]) # select random slice snake_case__ = int(ids_tensor((1,) , output_from_past.shape[-1])) snake_case__ = output_from_no_past[:, -3:, random_slice_idx] snake_case__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCamelCase__ , UpperCamelCase__ , rtol=1E-3) def _UpperCAmelCase ( a : str , a : Union[str, Any] , a : List[str] , a : str=None , a : int=None , a : int=None , a : int=None , a : Optional[int]=None , ): if attention_mask is None: snake_case__ = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: snake_case__ = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: snake_case__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: snake_case__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: snake_case__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase ): """simple docstring""" _lowercase : int = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () _lowercase : List[Any] = (TFPegasusForConditionalGeneration,) if is_tf_available() else () _lowercase : List[Any] = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) _lowercase : Optional[int] = True _lowercase : Dict = False _lowercase : Any = False def __magic_name__ ( self : str): '''simple docstring''' snake_case__ = TFPegasusModelTester(self) snake_case__ = ConfigTester(self , config_class=UpperCamelCase__) def __magic_name__ ( self : List[Any]): '''simple docstring''' self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[int]): '''simple docstring''' snake_case__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase__) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" _lowercase : List[str] = [ ''' 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 : str = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers _lowercase : int = '''google/pegasus-xsum''' @cached_property def __magic_name__ ( self : Dict): '''simple docstring''' return AutoTokenizer.from_pretrained(self.model_name) @cached_property def __magic_name__ ( self : int): '''simple docstring''' snake_case__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name) return model def __magic_name__ ( self : Dict , **UpperCamelCase__ : List[Any]): '''simple docstring''' snake_case__ = self.translate_src_text(**UpperCamelCase__) assert self.expected_text == generated_words def __magic_name__ ( self : str , **UpperCamelCase__ : List[Any]): '''simple docstring''' snake_case__ = self.tokenizer(self.src_text , **UpperCamelCase__ , padding=UpperCamelCase__ , return_tensors="""tf""") snake_case__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=UpperCamelCase__ , ) snake_case__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=UpperCamelCase__) return generated_words @slow def __magic_name__ ( self : List[str]): '''simple docstring''' self._assert_generated_batch_equal_expected()
654
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ : Union[str, Any] = logging.get_logger(__name__) lowercase_ : Tuple = { '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''', } class UpperCamelCase ( __SCREAMING_SNAKE_CASE ): A__ = """git_vision_model""" def __init__( self , snake_case__=768 , snake_case__=3072 , snake_case__=12 , snake_case__=12 , snake_case__=3 , snake_case__=224 , snake_case__=16 , snake_case__="quick_gelu" , snake_case__=1E-5 , snake_case__=0.0 , snake_case__=0.02 , **snake_case__ , ): """simple docstring""" super().__init__(**snake_case__ ) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Any = intermediate_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads _SCREAMING_SNAKE_CASE : Tuple = num_channels _SCREAMING_SNAKE_CASE : List[Any] = patch_size _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = initializer_range _SCREAMING_SNAKE_CASE : int = attention_dropout _SCREAMING_SNAKE_CASE : List[Any] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = hidden_act @classmethod def __SCREAMING_SNAKE_CASE ( cls , snake_case__ , **snake_case__ ): """simple docstring""" cls._set_token_in_kwargs(snake_case__ ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": _SCREAMING_SNAKE_CASE : Any = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(snake_case__ , **snake_case__ ) class UpperCamelCase ( __SCREAMING_SNAKE_CASE ): A__ = """git""" def __init__( self , snake_case__=None , snake_case__=30522 , snake_case__=768 , snake_case__=6 , snake_case__=12 , snake_case__=3072 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=1024 , snake_case__=0.02 , snake_case__=1E-12 , snake_case__=0 , snake_case__="absolute" , snake_case__=True , snake_case__=False , snake_case__=101 , snake_case__=102 , snake_case__=None , **snake_case__ , ): """simple docstring""" super().__init__(bos_token_id=snake_case__ , eos_token_id=snake_case__ , pad_token_id=snake_case__ , **snake_case__ ) if vision_config is None: _SCREAMING_SNAKE_CASE : List[str] = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) _SCREAMING_SNAKE_CASE : Optional[Any] = GitVisionConfig(**snake_case__ ) _SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = num_attention_heads _SCREAMING_SNAKE_CASE : Any = hidden_act _SCREAMING_SNAKE_CASE : Tuple = intermediate_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : Any = initializer_range _SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[Any] = position_embedding_type _SCREAMING_SNAKE_CASE : int = use_cache _SCREAMING_SNAKE_CASE : str = tie_word_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_image_with_embedding _SCREAMING_SNAKE_CASE : Optional[Any] = bos_token_id _SCREAMING_SNAKE_CASE : int = eos_token_id def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE : List[Any] = self.vision_config.to_dict() _SCREAMING_SNAKE_CASE : Optional[int] = self.__class__.model_type return output
295
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class UpperCamelCase ( __SCREAMING_SNAKE_CASE ): A__ = """naver-clova-ix/donut-base-finetuned-docvqa""" A__ = ( """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """ """should be the document containing the information, as well as a `question` that is the question about the """ """document. It returns a text that contains the answer to the question.""" ) A__ = """document_qa""" A__ = AutoProcessor A__ = VisionEncoderDecoderModel A__ = ["""image""", """text"""] A__ = ["""text"""] def __init__( self , *snake_case__ , **snake_case__ ): """simple docstring""" if not is_vision_available(): raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool." ) super().__init__(*snake_case__ , **snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" _SCREAMING_SNAKE_CASE : Optional[int] = task_prompt.replace("{user_input}" , snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = self.pre_processor.tokenizer( snake_case__ , add_special_tokens=snake_case__ , return_tensors="pt" ).input_ids _SCREAMING_SNAKE_CASE : Union[str, Any] = self.pre_processor(snake_case__ , return_tensors="pt" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" return self.model.generate( inputs["pixel_values"].to(self.device ) , decoder_input_ids=inputs["decoder_input_ids"].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=snake_case__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=snake_case__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=snake_case__ , ).sequences def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.pre_processor.batch_decode(snake_case__ )[0] _SCREAMING_SNAKE_CASE : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , "" ) _SCREAMING_SNAKE_CASE : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.pad_token , "" ) _SCREAMING_SNAKE_CASE : Dict = re.sub(r"<.*?>" , "" , snake_case__ , count=1 ).strip() # remove first task start token _SCREAMING_SNAKE_CASE : Dict = self.pre_processor.tokenajson(snake_case__ ) return sequence["answer"]
295
1
from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCamelCase =logging.get_logger(__name__) lowerCamelCase ={ "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class _lowerCamelCase ( UpperCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''mctct''' def __init__( self , __SCREAMING_SNAKE_CASE=8_0_6_5 , __SCREAMING_SNAKE_CASE=1_5_3_6 , __SCREAMING_SNAKE_CASE=3_6 , __SCREAMING_SNAKE_CASE=6_1_4_4 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_8_4 , __SCREAMING_SNAKE_CASE=9_2_0 , __SCREAMING_SNAKE_CASE=1e-5 , __SCREAMING_SNAKE_CASE=0.3 , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.3 , __SCREAMING_SNAKE_CASE=0.3 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0.3 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=(7,) , __SCREAMING_SNAKE_CASE=(3,) , __SCREAMING_SNAKE_CASE=8_0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="sum" , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE ) UpperCamelCase__ : str = vocab_size UpperCamelCase__ : Dict = hidden_size UpperCamelCase__ : Dict = num_hidden_layers UpperCamelCase__ : Optional[Any] = intermediate_size UpperCamelCase__ : str = num_attention_heads UpperCamelCase__ : str = attention_head_dim UpperCamelCase__ : List[str] = max_position_embeddings UpperCamelCase__ : Any = layer_norm_eps UpperCamelCase__ : Any = layerdrop UpperCamelCase__ : int = hidden_act UpperCamelCase__ : Optional[int] = initializer_range UpperCamelCase__ : List[str] = hidden_dropout_prob UpperCamelCase__ : Optional[int] = attention_probs_dropout_prob UpperCamelCase__ : List[str] = pad_token_id UpperCamelCase__ : Tuple = bos_token_id UpperCamelCase__ : Any = eos_token_id UpperCamelCase__ : Optional[Any] = conv_glu_dim UpperCamelCase__ : Union[str, Any] = conv_dropout UpperCamelCase__ : Any = num_conv_layers UpperCamelCase__ : List[str] = input_feat_per_channel UpperCamelCase__ : List[str] = input_channels UpperCamelCase__ : Tuple = conv_channels UpperCamelCase__ : List[str] = ctc_loss_reduction UpperCamelCase__ : str = ctc_zero_infinity # prevents config testing fail with exporting to json UpperCamelCase__ : Any = list(__SCREAMING_SNAKE_CASE ) UpperCamelCase__ : int = list(__SCREAMING_SNAKE_CASE ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.conv_kernel)` == `config.num_conv_layers` ''' F'''but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, ''' F'''`config.num_conv_layers = {self.num_conv_layers}`.''' )
285
def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ = 2_0_0_0_0_0_0 ): UpperCamelCase__ : Dict = [0 for i in range(n + 1 )] UpperCamelCase__ : Any = 1 UpperCamelCase__ : int = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , UpperCamelCase__ ): UpperCamelCase__ : Any = 1 UpperCamelCase__ : Optional[Any] = 0 for i in range(UpperCamelCase__ ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(F'''{solution() = }''')
285
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class _UpperCAmelCase ( snake_case ): __lowerCamelCase: int = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) __lowerCamelCase: List[Any] = 'CIDAS/clipseg-rd64-refined' __lowerCamelCase: List[str] = 'image_segmenter' __lowerCamelCase: Dict = CLIPSegForImageSegmentation __lowerCamelCase: Optional[int] = ['image', 'text'] __lowerCamelCase: Optional[int] = ['image'] def __init__( self : List[str] , *a : Dict , **a : Any ): '''simple docstring''' requires_backends(self , ["vision"] ) super().__init__(*a , **a ) def lowerCAmelCase__ ( self : int , a : "Image" , a : str ): '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=a , return_tensors="pt" ) def lowerCAmelCase__ ( self : int , a : Tuple ): '''simple docstring''' with torch.no_grad(): lowercase_ : str = self.model(**a ).logits return logits def lowerCAmelCase__ ( self : Optional[Any] , a : Tuple ): '''simple docstring''' lowercase_ : List[str] = outputs.cpu().detach().numpy() lowercase_ : Any = 0 lowercase_ : List[Any] = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
640
'''simple docstring''' from __future__ import annotations UpperCamelCase__ = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] UpperCamelCase__ = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" lowercase_ : str = [] lowercase_ : List[str] = len(_UpperCamelCase ) for i in range(_UpperCamelCase ): lowercase_ : float = -1 for j in range(i + 1 , _UpperCamelCase ): if arr[i] < arr[j]: lowercase_ : Union[str, Any] = arr[j] break result.append(_UpperCamelCase ) return result def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" lowercase_ : List[str] = [] for i, outer in enumerate(_UpperCamelCase ): lowercase_ : float = -1 for inner in arr[i + 1 :]: if outer < inner: lowercase_ : Optional[Any] = inner break result.append(_UpperCamelCase ) return result def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" lowercase_ : List[str] = len(_UpperCamelCase ) lowercase_ : list[float] = [] lowercase_ : list[float] = [-1] * arr_size for index in reversed(range(_UpperCamelCase ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: lowercase_ : Optional[Any] = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) UpperCamelCase__ = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
640
1
"""simple docstring""" from __future__ import annotations def __A ( a_ :float , a_ :float , a_ :float , ) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError('''You cannot supply more or less than 2 values''') elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative in a semiconductor''') elif hole_conc < 0: raise ValueError('''Hole concentration cannot be negative in a semiconductor''') elif intrinsic_conc < 0: raise ValueError( '''Intrinsic concentration cannot be negative in a semiconductor''') elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
52
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'RWKV/rwkv-4-169m-pile': 'https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json', 'RWKV/rwkv-4-430m-pile': 'https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json', 'RWKV/rwkv-4-1b5-pile': 'https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json', 'RWKV/rwkv-4-3b-pile': 'https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json', 'RWKV/rwkv-4-7b-pile': 'https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json', 'RWKV/rwkv-4-14b-pile': 'https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json', 'RWKV/rwkv-raven-1b5': 'https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json', 'RWKV/rwkv-raven-3b': 'https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json', 'RWKV/rwkv-raven-7b': 'https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json', 'RWKV/rwkv-raven-14b': 'https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json', } class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = '''rwkv''' UpperCamelCase : Optional[int] = {'''max_position_embeddings''': '''context_length'''} def __init__( self : List[Any] , UpperCAmelCase__ : Optional[int]=50277 , UpperCAmelCase__ : List[Any]=1024 , UpperCAmelCase__ : Dict=4096 , UpperCAmelCase__ : Optional[Any]=32 , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=1E-5 , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Any=6 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=True , **UpperCAmelCase__ : List[Any] , ) -> Optional[int]: _a : Dict = vocab_size _a : List[Any] = context_length _a : int = hidden_size _a : Dict = num_hidden_layers _a : List[Any] = attention_hidden_size if attention_hidden_size is not None else hidden_size _a : Any = intermediate_size if intermediate_size is not None else 4 * hidden_size _a : int = layer_norm_epsilon _a : List[str] = rescale_every _a : List[str] = use_cache _a : List[str] = bos_token_id _a : Optional[int] = eos_token_id super().__init__( tie_word_embeddings=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ )
389
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowercase : def __init__( self : Optional[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : str=3 , lowerCamelCase__ : Any=3_2 , lowerCamelCase__ : Union[str, Any]=3 , lowerCamelCase__ : Any=1_0 , lowerCamelCase__ : Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , lowerCamelCase__ : int=[1, 1, 2, 1] , lowerCamelCase__ : List[Any]=True , lowerCamelCase__ : Any=True , lowerCamelCase__ : str="relu" , lowerCamelCase__ : Tuple=3 , lowerCamelCase__ : str=None , ) -> Union[str, Any]: """simple docstring""" A_ = parent A_ = batch_size A_ = image_size A_ = num_channels A_ = embeddings_size A_ = hidden_sizes A_ = depths A_ = is_training A_ = use_labels A_ = hidden_act A_ = num_labels A_ = scope A_ = len(lowerCamelCase__ ) def UpperCamelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" A_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ = None if self.use_labels: A_ = ids_tensor([self.batch_size] , self.num_labels ) A_ = self.get_config() return config, pixel_values, labels def UpperCamelCase ( self : str ) -> Optional[Any]: """simple docstring""" return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCamelCase ( self : int , lowerCamelCase__ : int , lowerCamelCase__ : Dict , lowerCamelCase__ : Any ) -> Optional[int]: """simple docstring""" A_ = TFResNetModel(config=lowerCamelCase__ ) A_ = model(lowerCamelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def UpperCamelCase ( self : List[str] , lowerCamelCase__ : Any , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Union[str, Any] ) -> List[str]: """simple docstring""" A_ = self.num_labels A_ = TFResNetForImageClassification(lowerCamelCase__ ) A_ = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" A_ = self.prepare_config_and_inputs() A_ ,A_ ,A_ = config_and_inputs A_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class _lowercase ( __lowerCamelCase,__lowerCamelCase,unittest.TestCase ): _lowercase : Dict = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Optional[int] = ( {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : List[Any] = False _lowercase : Union[str, Any] = False _lowercase : str = False _lowercase : Optional[int] = False _lowercase : List[Any] = False def UpperCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" A_ = TFResNetModelTester(self ) A_ = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ ) def UpperCamelCase ( self : int ) -> List[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return @unittest.skip(reason='''ResNet does not use inputs_embeds''' ) def UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" pass @unittest.skip(reason='''ResNet does not support input and output embeddings''' ) def UpperCamelCase ( self : str ) -> Dict: """simple docstring""" pass def UpperCamelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ = model_class(lowerCamelCase__ ) A_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ = [*signature.parameters.keys()] A_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def UpperCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def UpperCamelCase ( self : int ) -> Union[str, Any]: """simple docstring""" def check_hidden_states_output(lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] ): A_ = model_class(lowerCamelCase__ ) A_ = model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) A_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A_ = self.model_tester.num_stages self.assertEqual(len(lowerCamelCase__ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: A_ = layer_type A_ = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A_ = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def UpperCamelCase ( self : Tuple ) -> Dict: """simple docstring""" A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) @slow def UpperCamelCase ( self : Dict ) -> str: """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ = TFResNetModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def _lowerCamelCase ( ): '''simple docstring''' A_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class _lowercase ( unittest.TestCase ): @cached_property def UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" A_ = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) A_ = self.default_image_processor A_ = prepare_img() A_ = image_processor(images=lowerCamelCase__ , return_tensors='''tf''' ) # forward pass A_ = model(**lowerCamelCase__ ) # verify the logits A_ = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) A_ = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCamelCase__ , atol=1e-4 ) )
563
from __future__ import annotations def _lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if len(SCREAMING_SNAKE_CASE ) == 0: return [] A_ ,A_ = min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) A_ = int(max_value - min_value ) + 1 A_ = [[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
563
1
"""simple docstring""" from __future__ import annotations def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : int = get_failure_array(_lowerCamelCase ) # 2) Step through text searching for pattern _lowerCAmelCase, _lowerCAmelCase : Optional[int] = 0, 0 # index into text, pattern while i < len(_lowerCamelCase ): if pattern[j] == text[i]: if j == (len(_lowerCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _lowerCAmelCase : List[str] = failure[j - 1] continue i += 1 return False def lowerCamelCase__ ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[str] = [0] _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : Union[str, Any] = 1 while j < len(_lowerCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _lowerCAmelCase : List[str] = failure[i - 1] continue j += 1 failure.append(_lowerCamelCase ) return failure if __name__ == "__main__": # Test 1) _lowerCAmelCase = """abc1abc12""" _lowerCAmelCase = """alskfjaldsabc1abc1abc12k23adsfabcabc""" _lowerCAmelCase = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) _lowerCAmelCase = """ABABX""" _lowerCAmelCase = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) _lowerCAmelCase = """AAAB""" _lowerCAmelCase = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) _lowerCAmelCase = """abcdabcy""" _lowerCAmelCase = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) _lowerCAmelCase = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
259
from __future__ import annotations def __A(lowerCAmelCase , lowerCAmelCase ) -> list[list[int]]: """simple docstring""" _UpperCamelCase = [] _UpperCamelCase = [] _UpperCamelCase = 0 _UpperCamelCase = sum(lowerCAmelCase ) create_state_space_tree(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return result def __A(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ) -> None: """simple docstring""" if sum(lowerCAmelCase ) > max_sum or (remaining_nums_sum + sum(lowerCAmelCase )) < max_sum: return if sum(lowerCAmelCase ) == max_sum: result.append(lowerCAmelCase ) return for index in range(lowerCAmelCase , len(lowerCAmelCase ) ): create_state_space_tree( lowerCAmelCase , lowerCAmelCase , index + 1 , [*path, nums[index]] , lowerCAmelCase , remaining_nums_sum - nums[index] , ) lowerCamelCase__ = [3, 34, 4, 12, 5, 2] lowerCamelCase__ = 9 lowerCamelCase__ = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
612
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a = { """configuration_deberta""": ["""DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DebertaConfig""", """DebertaOnnxConfig"""], """tokenization_deberta""": ["""DebertaTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = ["""DebertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ """DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """DebertaForMaskedLM""", """DebertaForQuestionAnswering""", """DebertaForSequenceClassification""", """DebertaForTokenClassification""", """DebertaModel""", """DebertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ """TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFDebertaForMaskedLM""", """TFDebertaForQuestionAnswering""", """TFDebertaForSequenceClassification""", """TFDebertaForTokenClassification""", """TFDebertaModel""", """TFDebertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
704
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class UpperCAmelCase_ (snake_case__ ): """simple docstring""" lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
382
0
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging SCREAMING_SNAKE_CASE :List[Any] = logging.get_logger(__name__) def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = r"\w+[.]\d+" __A = re.findall(__UpperCamelCase , __UpperCamelCase ) for pat in pats: __A = key.replace(__UpperCamelCase , "_".join(pat.split("." ) ) ) return key def UpperCAmelCase ( a_ , a_ , a_ ) -> Union[str, Any]: """simple docstring""" __A = pt_tuple_key[:-1] + ("scale",) if ( any("norm" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): __A = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: __A = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: __A = pt_tuple_key[:-1] + ("embedding",) return renamed_pt_tuple_key, pt_tensor # conv layer __A = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: __A = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer __A = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight": __A = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight __A = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias __A = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCAmelCase ( a_ , a_ , a_=4_2 ) -> Optional[int]: """simple docstring""" __A = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params __A = flax_model.init_weights(PRNGKey(__UpperCamelCase ) ) __A = flatten_dict(__UpperCamelCase ) __A = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): __A = rename_key(__UpperCamelCase ) __A = tuple(renamed_pt_key.split("." ) ) # Correctly rename weight parameters __A , __A = rename_key_and_reshape_tensor(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' F'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # also add unexpected weight so that warning is thrown __A = jnp.asarray(__UpperCamelCase ) return unflatten_dict(__UpperCamelCase )
55
def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> int: if exponent == 1: return base if exponent % 2 == 0: A__ = _modexpt(__UpperCamelCase , exponent // 2 , __UpperCamelCase ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(__UpperCamelCase , exponent - 1 , __UpperCamelCase )) % modulo_value def A ( __UpperCamelCase = 1_777 , __UpperCamelCase = 1_855 , __UpperCamelCase = 8 ) -> int: A__ = base for _ in range(1 , __UpperCamelCase ): A__ = _modexpt(__UpperCamelCase , __UpperCamelCase , 10**digits ) return result if __name__ == "__main__": print(f'{solution() = }')
9
0
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("key_a", "val_b"), ] @pytest.mark.parametrize( 'operations' , ( pytest.param(_add_items , id='add items' ), pytest.param(_overwrite_items , id='overwrite items' ), pytest.param(_delete_items , id='delete items' ), pytest.param(_access_absent_items , id='access absent items' ), pytest.param(_add_with_resize_up , id='add with resize up' ), pytest.param(_add_with_resize_down , id='add with resize down' ), ) , ) def lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
719
'''simple docstring''' import os import sys import unittest __UpperCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase = os.path.join(git_repo_path, "src", "transformers") __UpperCAmelCase = "\n{0} = None\n" __UpperCAmelCase = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" __UpperCAmelCase = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' ) self.assertIsNone(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = find_backend(' if not is_tokenizers_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tokenizers' ) snake_case: List[Any] = find_backend(' if not is_tensorflow_text_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tensorflow_text' ) snake_case: int = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers' ) snake_case: Optional[Any] = find_backend( ' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tensorflow_text' ) snake_case: Dict = find_backend( ' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers_and_vision' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , SCREAMING_SNAKE_CASE__ ) self.assertIn('tensorflow_text' , SCREAMING_SNAKE_CASE__ ) self.assertIn('sentencepiece_and_tokenizers' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertModel' , objects['tf'] ) self.assertIn('FlaxBertModel' , objects['flax'] ) self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] ) self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '\nCONSTANT = None\n' ) snake_case: Any = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) snake_case: Optional[int] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n' snake_case: Tuple = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n' snake_case: Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , SCREAMING_SNAKE_CASE__ )
692
0
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
from statistics import mean, stdev def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list , SCREAMING_SNAKE_CASE_: int = 3 ) -> list: '''simple docstring''' A__ = min(SCREAMING_SNAKE_CASE_ ) A__ = max(SCREAMING_SNAKE_CASE_ ) # normalize data return [round((x - x_min) / (x_max - x_min) , SCREAMING_SNAKE_CASE_ ) for x in data] def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list , SCREAMING_SNAKE_CASE_: int = 3 ) -> list: '''simple docstring''' A__ = mean(SCREAMING_SNAKE_CASE_ ) A__ = stdev(SCREAMING_SNAKE_CASE_ ) # standardize data return [round((x - mu) / (sigma) , SCREAMING_SNAKE_CASE_ ) for x in data]
514
0
'''simple docstring''' _lowercase : str =9.8_0_6_6_5 def A__ ( lowercase: float, lowercase: float, lowercase: float = g ) -> float: if fluid_density <= 0: raise ValueError('Impossible fluid density' ) if volume < 0: raise ValueError('Impossible Object volume' ) if gravity <= 0: raise ValueError('Impossible Gravity' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
720
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' _lowercase : List[Any] = KandinskyVaaImgaImgPipeline _lowercase : List[Any] = ['''image_embeds''', '''negative_image_embeds''', '''image'''] _lowercase : str = [ '''image_embeds''', '''negative_image_embeds''', '''image''', ] _lowercase : int = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _lowercase : str = False @property def _lowercase ( self ): """simple docstring""" return 32 @property def _lowercase ( self ): """simple docstring""" return 32 @property def _lowercase ( self ): """simple docstring""" return self.time_input_dim @property def _lowercase ( self ): """simple docstring""" return self.time_input_dim * 4 @property def _lowercase ( self ): """simple docstring""" return 100 @property def _lowercase ( self ): """simple docstring""" torch.manual_seed(0 ) _lowerCAmelCase = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase = UNetaDConditionModel(**_lowercase ) return model @property def _lowercase ( self ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _lowercase ( self ): """simple docstring""" torch.manual_seed(0 ) _lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.dummy_unet _lowerCAmelCase = self.dummy_movq _lowerCAmelCase = { """num_train_timesteps""": 1_000, """beta_schedule""": """linear""", """beta_start""": 0.0_0085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _lowerCAmelCase = DDIMScheduler(**_lowercase ) _lowerCAmelCase = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def _lowercase ( self , _lowercase , _lowercase=0 ): """simple docstring""" _lowerCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowercase ) ).to(_lowercase ) _lowerCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowercase ) # create init_image _lowerCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowercase ) ).to(_lowercase ) _lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(_lowercase ) ).convert("""RGB""" ).resize((256, 256) ) if str(_lowercase ).startswith("""mps""" ): _lowerCAmelCase = torch.manual_seed(_lowercase ) else: _lowerCAmelCase = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) _lowerCAmelCase = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = """cpu""" _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = self.pipeline_class(**_lowercase ) _lowerCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) _lowerCAmelCase = pipe(**self.get_dummy_inputs(_lowercase ) ) _lowerCAmelCase = output.images _lowerCAmelCase = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] _lowerCAmelCase = image[0, -3:, -3:, -1] _lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase = np.array( [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_img2img_frog.npy""" ) _lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase = """A red cartoon frog, 4k""" _lowerCAmelCase = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_lowercase ) _lowerCAmelCase = KandinskyVaaImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) _lowerCAmelCase = pipeline.to(_lowercase ) pipeline.set_progress_bar_config(disable=_lowercase ) _lowerCAmelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase = pipe_prior( _lowercase , generator=_lowercase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase = pipeline( image=_lowercase , image_embeds=_lowercase , negative_image_embeds=_lowercase , generator=_lowercase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowercase , _lowercase )
5
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def A (__lowerCamelCase :List[Any] ): _lowerCAmelCase = 384 if "tiny" in model_name: _lowerCAmelCase = [3, 3, 9, 3] _lowerCAmelCase = [96, 192, 384, 768] if "small" in model_name: _lowerCAmelCase = [3, 3, 27, 3] _lowerCAmelCase = [96, 192, 384, 768] if "base" in model_name: _lowerCAmelCase = [3, 3, 27, 3] _lowerCAmelCase = [128, 256, 512, 1024] _lowerCAmelCase = 512 if "large" in model_name: _lowerCAmelCase = [3, 3, 27, 3] _lowerCAmelCase = [192, 384, 768, 1536] _lowerCAmelCase = 768 if "xlarge" in model_name: _lowerCAmelCase = [3, 3, 27, 3] _lowerCAmelCase = [256, 512, 1024, 2048] _lowerCAmelCase = 1024 # set label information _lowerCAmelCase = 150 _lowerCAmelCase = """huggingface/label-files""" _lowerCAmelCase = """ade20k-id2label.json""" _lowerCAmelCase = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _lowerCAmelCase = {int(__lowerCamelCase ): v for k, v in idalabel.items()} _lowerCAmelCase = {v: k for k, v in idalabel.items()} _lowerCAmelCase = ConvNextConfig( depths=__lowerCamelCase , hidden_sizes=__lowerCamelCase , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) _lowerCAmelCase = UperNetConfig( backbone_config=__lowerCamelCase , auxiliary_in_channels=__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase , ) return config def A (__lowerCamelCase :Optional[Any] ): _lowerCAmelCase = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'backbone.stages.{i}.{j}.gamma', f'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter') ) rename_keys.append((f'backbone.stages.{i}.{j}.depthwise_conv.weight', f'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight') ) rename_keys.append((f'backbone.stages.{i}.{j}.depthwise_conv.bias', f'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias') ) rename_keys.append((f'backbone.stages.{i}.{j}.norm.weight', f'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight') ) rename_keys.append((f'backbone.stages.{i}.{j}.norm.bias', f'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias') ) rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv1.weight', f'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight') ) rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv1.bias', f'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias') ) rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv2.weight', f'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight') ) rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv2.bias', f'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias') ) if i > 0: rename_keys.append((f'backbone.downsample_layers.{i}.0.weight', f'backbone.encoder.stages.{i}.downsampling_layer.0.weight') ) rename_keys.append((f'backbone.downsample_layers.{i}.0.bias', f'backbone.encoder.stages.{i}.downsampling_layer.0.bias') ) rename_keys.append((f'backbone.downsample_layers.{i}.1.weight', f'backbone.encoder.stages.{i}.downsampling_layer.1.weight') ) rename_keys.append((f'backbone.downsample_layers.{i}.1.bias', f'backbone.encoder.stages.{i}.downsampling_layer.1.bias') ) rename_keys.append((f'backbone.norm{i}.weight', f'backbone.hidden_states_norms.stage{i+1}.weight') ) rename_keys.append((f'backbone.norm{i}.bias', f'backbone.hidden_states_norms.stage{i+1}.bias') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def A (__lowerCamelCase :Optional[Any] , __lowerCamelCase :Dict , __lowerCamelCase :Tuple ): _lowerCAmelCase = dct.pop(__lowerCamelCase ) _lowerCAmelCase = val def A (__lowerCamelCase :Union[str, Any] , __lowerCamelCase :Optional[Any] , __lowerCamelCase :Any ): _lowerCAmelCase = { """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""", """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""", """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""", """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""", """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""", } _lowerCAmelCase = model_name_to_url[model_name] _lowerCAmelCase = torch.hub.load_state_dict_from_url(__lowerCamelCase , map_location="""cpu""" )["""state_dict"""] _lowerCAmelCase = get_upernet_config(__lowerCamelCase ) _lowerCAmelCase = UperNetForSemanticSegmentation(__lowerCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _lowerCAmelCase = state_dict.pop(__lowerCamelCase ) if "bn" in key: _lowerCAmelCase = key.replace("""bn""" , """batch_norm""" ) _lowerCAmelCase = val # rename keys _lowerCAmelCase = create_rename_keys(__lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) # verify on image _lowerCAmelCase = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" _lowerCAmelCase = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ).convert("""RGB""" ) _lowerCAmelCase = SegformerImageProcessor() _lowerCAmelCase = processor(__lowerCamelCase , return_tensors="""pt""" ).pixel_values with torch.no_grad(): _lowerCAmelCase = model(__lowerCamelCase ) if model_name == "upernet-convnext-tiny": _lowerCAmelCase = torch.tensor( [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]] ) elif model_name == "upernet-convnext-small": _lowerCAmelCase = torch.tensor( [[-8.8_236, -8.8_236, -8.6_771], [-8.8_236, -8.8_236, -8.6_771], [-8.7_638, -8.7_638, -8.6_240]] ) elif model_name == "upernet-convnext-base": _lowerCAmelCase = torch.tensor( [[-8.8_558, -8.8_558, -8.6_905], [-8.8_558, -8.8_558, -8.6_905], [-8.7_669, -8.7_669, -8.6_021]] ) elif model_name == "upernet-convnext-large": _lowerCAmelCase = torch.tensor( [[-8.6_660, -8.6_660, -8.6_210], [-8.6_660, -8.6_660, -8.6_210], [-8.6_310, -8.6_310, -8.5_964]] ) elif model_name == "upernet-convnext-xlarge": _lowerCAmelCase = torch.tensor( [[-8.4_980, -8.4_980, -8.3_977], [-8.4_980, -8.4_980, -8.3_977], [-8.4_379, -8.4_379, -8.3_412]] ) print("""Logits:""" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , __lowerCamelCase , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCamelCase ) print(f'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(__lowerCamelCase ) if push_to_hub: print(f'Pushing model and processor for {model_name} to hub' ) model.push_to_hub(f'openmmlab/{model_name}' ) processor.push_to_hub(f'openmmlab/{model_name}' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[F"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) _lowercase = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
5
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
713
'''simple docstring''' import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( lowercase : str , lowercase : str , lowercase : str ) ->Any: """simple docstring""" def get_masked_lm_array(lowercase : str ): lowercase__ = F'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' lowercase__ = tf.train.load_variable(lowercase , lowercase ) if "kernel" in name: lowercase__ = array.transpose() return torch.from_numpy(lowercase ) def get_encoder_array(lowercase : str ): lowercase__ = F'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' lowercase__ = tf.train.load_variable(lowercase , lowercase ) if "kernel" in name: lowercase__ = array.transpose() return torch.from_numpy(lowercase ) def get_encoder_layer_array(lowercase : int , lowercase : str ): lowercase__ = F'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' lowercase__ = tf.train.load_variable(lowercase , lowercase ) if "kernel" in name: lowercase__ = array.transpose() return torch.from_numpy(lowercase ) def get_encoder_attention_layer_array(lowercase : int , lowercase : str , lowercase : Any ): lowercase__ = F'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' lowercase__ = tf.train.load_variable(lowercase , lowercase ) lowercase__ = array.reshape(lowercase ) if "kernel" in name: lowercase__ = array.transpose() return torch.from_numpy(lowercase ) print(F'''Loading model based on config from {config_path}...''' ) lowercase__ = BertConfig.from_json_file(lowercase ) lowercase__ = BertForMaskedLM(lowercase ) # Layers for layer_index in range(0 , config.num_hidden_layers ): lowercase__ = model.bert.encoder.layer[layer_index] # Self-attention lowercase__ = layer.attention.self lowercase__ = get_encoder_attention_layer_array( lowercase , '''_query_dense/kernel''' , self_attn.query.weight.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_query_dense/bias''' , self_attn.query.bias.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_key_dense/kernel''' , self_attn.key.weight.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_key_dense/bias''' , self_attn.key.bias.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_value_dense/kernel''' , self_attn.value.weight.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_value_dense/bias''' , self_attn.value.bias.data.shape ) # Self-attention Output lowercase__ = layer.attention.output lowercase__ = get_encoder_attention_layer_array( lowercase , '''_output_dense/kernel''' , self_output.dense.weight.data.shape ) lowercase__ = get_encoder_attention_layer_array( lowercase , '''_output_dense/bias''' , self_output.dense.bias.data.shape ) lowercase__ = get_encoder_layer_array(lowercase , '''_attention_layer_norm/gamma''' ) lowercase__ = get_encoder_layer_array(lowercase , '''_attention_layer_norm/beta''' ) # Intermediate lowercase__ = layer.intermediate lowercase__ = get_encoder_layer_array(lowercase , '''_intermediate_dense/kernel''' ) lowercase__ = get_encoder_layer_array(lowercase , '''_intermediate_dense/bias''' ) # Output lowercase__ = layer.output lowercase__ = get_encoder_layer_array(lowercase , '''_output_dense/kernel''' ) lowercase__ = get_encoder_layer_array(lowercase , '''_output_dense/bias''' ) lowercase__ = get_encoder_layer_array(lowercase , '''_output_layer_norm/gamma''' ) lowercase__ = get_encoder_layer_array(lowercase , '''_output_layer_norm/beta''' ) # Embeddings lowercase__ = get_encoder_array('''_position_embedding_layer/embeddings''' ) lowercase__ = get_encoder_array('''_type_embedding_layer/embeddings''' ) lowercase__ = get_encoder_array('''_embedding_norm_layer/gamma''' ) lowercase__ = get_encoder_array('''_embedding_norm_layer/beta''' ) # LM Head lowercase__ = model.cls.predictions.transform lowercase__ = get_masked_lm_array('''dense/kernel''' ) lowercase__ = get_masked_lm_array('''dense/bias''' ) lowercase__ = get_masked_lm_array('''layer_norm/gamma''' ) lowercase__ = get_masked_lm_array('''layer_norm/beta''' ) lowercase__ = get_masked_lm_array('''embedding_table''' ) # Pooling lowercase__ = BertPooler(config=lowercase ) lowercase__ = get_encoder_array('''_pooler_layer/kernel''' ) lowercase__ = get_encoder_array('''_pooler_layer/bias''' ) # Export final model model.save_pretrained(lowercase ) # Integration test - should load without any errors ;) lowercase__ = BertForMaskedLM.from_pretrained(lowercase ) print(new_model.eval() ) print('''Model conversion was done sucessfully!''' ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path." ) parser.add_argument( "--bert_config_file", type=str, required=True, help="The config json file corresponding to the BERT model. This specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", type=str, required=True, help="Path to the output PyTorch model.", ) _lowerCAmelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
318
0
'''simple docstring''' import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __A =logging.get_logger(__name__) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Any = set() UpperCAmelCase__ : List[Any] = [] def parse_line(UpperCamelCase__ ): for line in fp: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Union[str, Any] = line.decode("""UTF-8""" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(""" """ ): # process a single warning and move it to `selected_warnings`. if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Dict = """\n""".join(UpperCamelCase__ ) # Only keep the warnings specified in `targets` if any(f''': {x}: ''' in warning for x in targets ): selected_warnings.add(UpperCamelCase__ ) buffer.clear() continue else: UpperCAmelCase__ : int = line.strip() buffer.append(UpperCamelCase__ ) if from_gh: for filename in os.listdir(UpperCamelCase__ ): UpperCAmelCase__ : Tuple = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) if not os.path.isdir(UpperCamelCase__ ): # read the file if filename != "warnings.txt": continue with open(UpperCamelCase__ ) as fp: parse_line(UpperCamelCase__ ) else: try: with zipfile.ZipFile(UpperCamelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase__ ): # read the file if filename != "warnings.txt": continue with z.open(UpperCamelCase__ ) as fp: parse_line(UpperCamelCase__ ) except Exception: logger.warning( f'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Optional[Any] = set() UpperCAmelCase__ : List[Any] = [os.path.join(UpperCamelCase__ , UpperCamelCase__ ) for p in os.listdir(UpperCamelCase__ ) if (p.endswith(""".zip""" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(UpperCamelCase__ , UpperCamelCase__ ) ) return selected_warnings if __name__ == "__main__": def _UpperCamelCase ( UpperCamelCase__ ): return values.split(""",""" ) __A =argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') # optional parameters parser.add_argument( '--targets', default='DeprecationWarning,UserWarning,FutureWarning', type=list_str, help='Comma-separated list of target warning(s) which we want to extract.', ) parser.add_argument( '--from_gh', action='store_true', help='If running from a GitHub action workflow and collecting warnings from its artifacts.', ) __A =parser.parse_args() __A =args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __A =get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('=' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __A =extract_warnings(args.output_dir, args.targets) __A =sorted(selected_warnings) with open(os.path.join(args.output_dir, 'selected_warnings.json'), 'w', encoding='UTF-8') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
407
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class _snake_case ( a__ ): def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = False , **_lowerCamelCase , ): super().__init__(features=_lowerCamelCase , cache_dir=_lowerCamelCase , keep_in_memory=_lowerCamelCase , **_lowerCamelCase) UpperCAmelCase__ : Optional[Any] = Sql( cache_dir=_lowerCamelCase , features=_lowerCamelCase , sql=_lowerCamelCase , con=_lowerCamelCase , **_lowerCamelCase , ) def snake_case__ ( self): UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : int = None UpperCAmelCase__ : List[Any] = None UpperCAmelCase__ : List[Any] = None self.builder.download_and_prepare( download_config=_lowerCamelCase , download_mode=_lowerCamelCase , verification_mode=_lowerCamelCase , base_path=_lowerCamelCase , ) # Build dataset for splits UpperCAmelCase__ : Union[str, Any] = self.builder.as_dataset( split="""train""" , verification_mode=_lowerCamelCase , in_memory=self.keep_in_memory) return dataset class _snake_case : def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , **_lowerCamelCase , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''') UpperCAmelCase__ : Optional[Any] = dataset UpperCAmelCase__ : Optional[int] = name UpperCAmelCase__ : str = con UpperCAmelCase__ : Optional[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCAmelCase__ : Union[str, Any] = num_proc UpperCAmelCase__ : List[str] = to_sql_kwargs def snake_case__ ( self): UpperCAmelCase__ : Optional[Any] = self.to_sql_kwargs.pop("""sql""" , _lowerCamelCase) UpperCAmelCase__ : List[Any] = self.to_sql_kwargs.pop("""con""" , _lowerCamelCase) UpperCAmelCase__ : int = self.to_sql_kwargs.pop("""index""" , _lowerCamelCase) UpperCAmelCase__ : Any = self._write(index=_lowerCamelCase , **self.to_sql_kwargs) return written def snake_case__ ( self , _lowerCamelCase): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = args UpperCAmelCase__ : Tuple = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs UpperCAmelCase__ : str = query_table( table=self.dataset.data , key=slice(_lowerCamelCase , offset + self.batch_size) , indices=self.dataset._indices , ) UpperCAmelCase__ : List[str] = batch.to_pandas() UpperCAmelCase__ : List[str] = df.to_sql(self.name , self.con , index=_lowerCamelCase , **_lowerCamelCase) return num_rows or len(_lowerCamelCase) def snake_case__ ( self , _lowerCamelCase , **_lowerCamelCase): UpperCAmelCase__ : Dict = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset) , self.batch_size) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs)) else: UpperCAmelCase__ , UpperCAmelCase__ : Dict = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _lowerCamelCase , _lowerCamelCase)] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
407
1
from __future__ import annotations __magic_name__ = tuple[int, int, int] __magic_name__ = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __magic_name__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- __magic_name__ = '''EGZWVONAHDCLFQMSIPJBYUKXTR''' __magic_name__ = '''FOBHMDKEXQNRAULPGSJVTYICZW''' __magic_name__ = '''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- __magic_name__ = { '''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 -------------------------- __magic_name__ = '''RMDJXFUWGISLHVTCQNKYPBEZOA''' __magic_name__ = '''SGLCPQWZHKXAREONTFBVIYJUDM''' __magic_name__ = '''HVSICLTYKQUBXDWAJZOMFGPREN''' __magic_name__ = '''RZWQHFMVDBKICJLNTUXAGYPSOE''' __magic_name__ = '''LFKIJODBEGAMQPXVUHYSTCZRWN''' __magic_name__ = '''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" if (unique_rotsel := len(set(_UpperCAmelCase ) )) < 3: lowercase = f"""Please use 3 unique rotors (not {unique_rotsel})""" raise Exception(_UpperCAmelCase ) # Checks if rotor positions are valid lowercase , lowercase , lowercase = rotpos if not 0 < rotorposa <= len(_UpperCAmelCase ): lowercase = f"""First rotor position is not within range of 1..26 ({rotorposa}""" raise ValueError(_UpperCAmelCase ) if not 0 < rotorposa <= len(_UpperCAmelCase ): lowercase = f"""Second rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_UpperCAmelCase ) if not 0 < rotorposa <= len(_UpperCAmelCase ): lowercase = f"""Third rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_UpperCAmelCase ) # Validates string and returns dict lowercase = _plugboard(_UpperCAmelCase ) return rotpos, rotsel, pbdict def __snake_case ( _UpperCAmelCase ): """simple docstring""" if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowercase = f"""Plugboard setting isn't type string ({type(_UpperCAmelCase )})""" raise TypeError(_UpperCAmelCase ) elif len(_UpperCAmelCase ) % 2 != 0: lowercase = f"""Odd number of symbols ({len(_UpperCAmelCase )})""" raise Exception(_UpperCAmelCase ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowercase = set() for i in pbstring: if i not in abc: lowercase = f"""'{i}' not in list of symbols""" raise Exception(_UpperCAmelCase ) elif i in tmppbl: lowercase = f"""Duplicate symbol ({i})""" raise Exception(_UpperCAmelCase ) else: tmppbl.add(_UpperCAmelCase ) del tmppbl # Created the dictionary lowercase = {} for j in range(0 , len(_UpperCAmelCase ) - 1 , 2 ): lowercase = pbstring[j + 1] lowercase = pbstring[j] return pb def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = (rotora, rotora, rotora) , _UpperCAmelCase = "" , ): """simple docstring""" lowercase = text.upper() lowercase , lowercase , lowercase = _validator( _UpperCAmelCase , _UpperCAmelCase , plugb.upper() ) lowercase , lowercase , lowercase = rotor_position lowercase , lowercase , lowercase = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowercase = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowercase = plugboard[symbol] # rotor ra -------------------------- lowercase = abc.index(_UpperCAmelCase ) + rotorposa lowercase = rotora[index % len(_UpperCAmelCase )] # rotor rb -------------------------- lowercase = abc.index(_UpperCAmelCase ) + rotorposa lowercase = rotora[index % len(_UpperCAmelCase )] # rotor rc -------------------------- lowercase = abc.index(_UpperCAmelCase ) + rotorposa lowercase = rotora[index % len(_UpperCAmelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowercase = reflector[symbol] # 2nd rotors lowercase = abc[rotora.index(_UpperCAmelCase ) - rotorposa] lowercase = abc[rotora.index(_UpperCAmelCase ) - rotorposa] lowercase = abc[rotora.index(_UpperCAmelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowercase = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowercase = 0 rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowercase = 0 rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowercase = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_UpperCAmelCase ) return "".join(_UpperCAmelCase ) if __name__ == "__main__": __magic_name__ = '''This is my Python script that emulates the Enigma machine from WWII.''' __magic_name__ = (1, 1, 1) __magic_name__ = '''pictures''' __magic_name__ = (rotora, rotora, rotora) __magic_name__ = enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
703
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def __snake_case ( _UpperCAmelCase ): """simple docstring""" if "model" in orig_key: lowercase = orig_key.replace('model.' , '' ) if "norm1" in orig_key: lowercase = orig_key.replace('norm1' , 'attention.output.LayerNorm' ) if "norm2" in orig_key: lowercase = orig_key.replace('norm2' , 'output.LayerNorm' ) if "norm" in orig_key: lowercase = orig_key.replace('norm' , 'LayerNorm' ) if "transformer" in orig_key: lowercase = orig_key.split('.' )[0].split('_' )[-1] lowercase = orig_key.replace(f"""transformer_{layer_num}""" , f"""encoder.layer.{layer_num}""" ) if "mha.attn" in orig_key: lowercase = orig_key.replace('mha.attn' , 'attention.self' ) if "mha" in orig_key: lowercase = orig_key.replace('mha' , 'attention' ) if "W_q" in orig_key: lowercase = orig_key.replace('W_q' , 'self.query' ) if "W_k" in orig_key: lowercase = orig_key.replace('W_k' , 'self.key' ) if "W_v" in orig_key: lowercase = orig_key.replace('W_v' , 'self.value' ) if "ff1" in orig_key: lowercase = orig_key.replace('ff1' , 'intermediate.dense' ) if "ff2" in orig_key: lowercase = orig_key.replace('ff2' , 'output.dense' ) if "ff" in orig_key: lowercase = orig_key.replace('ff' , 'output.dense' ) if "mlm_class" in orig_key: lowercase = orig_key.replace('mlm.mlm_class' , 'cls.predictions.decoder' ) if "mlm" in orig_key: lowercase = orig_key.replace('mlm' , 'cls.predictions.transform' ) if "cls" not in orig_key: lowercase = 'yoso.' + orig_key return orig_key def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" for key in orig_state_dict.copy().keys(): lowercase = orig_state_dict.pop(_UpperCAmelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: lowercase = val lowercase = orig_state_dict['cls.predictions.decoder.bias'] lowercase = torch.arange(_UpperCAmelCase ).expand((1, -1) ) + 2 return orig_state_dict def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" lowercase = torch.load(_UpperCAmelCase , map_location='cpu' )['model_state_dict'] lowercase = YosoConfig.from_json_file(_UpperCAmelCase ) lowercase = YosoForMaskedLM(_UpperCAmelCase ) lowercase = convert_checkpoint_helper(config.max_position_embeddings , _UpperCAmelCase ) print(model.load_state_dict(_UpperCAmelCase ) ) model.eval() model.save_pretrained(_UpperCAmelCase ) print(f"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--pytorch_model_path''', default=None, type=str, required=True, help='''Path to YOSO pytorch checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The json file for YOSO model config.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __magic_name__ = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
314
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''upernet''' def __init__( self : Union[str, Any] , __UpperCAmelCase : int=None , __UpperCAmelCase : Any=512 , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : Optional[Any]=[1, 2, 3, 6] , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Union[str, Any]=0.4 , __UpperCAmelCase : str=384 , __UpperCAmelCase : Optional[Any]=256 , __UpperCAmelCase : Optional[Any]=1 , __UpperCAmelCase : Dict=False , __UpperCAmelCase : Union[str, Any]=255 , **__UpperCAmelCase : List[Any] , ) ->Tuple: """simple docstring""" super().__init__(**snake_case__ ) if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a = CONFIG_MAPPING["resnet"](out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) elif isinstance(snake_case__ , snake_case__ ): a = backbone_config.get('''model_type''' ) a = CONFIG_MAPPING[backbone_model_type] a = config_class.from_dict(snake_case__ ) a = backbone_config a = hidden_size a = initializer_range a = pool_scales a = use_auxiliary_head a = auxiliary_loss_weight a = auxiliary_in_channels a = auxiliary_channels a = auxiliary_num_convs a = auxiliary_concat_input a = loss_ignore_index def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = copy.deepcopy(self.__dict__ ) a = self.backbone_config.to_dict() a = self.__class__.model_type return output
117
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : int )-> str: '''simple docstring''' if not isinstance(snake_case , snake_case ): raise ValueError("iterations must be defined as integers" ) if not isinstance(snake_case , snake_case ) or not number >= 1: raise ValueError( "starting number must be\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) UpperCAmelCase__ : str = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(snake_case ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
438
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def lowercase ( self : Any ): _snake_case = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=_lowerCamelCase ).to(_lowerCamelCase ) _snake_case = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _snake_case = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _snake_case = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _snake_case = model(input_ids.to(_lowerCamelCase ) , labels=labels.to(_lowerCamelCase ) ).loss _snake_case = -(labels.shape[-1] * loss.item()) _snake_case = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
430
"""simple docstring""" import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) def _UpperCAmelCase ( __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ) -> List[Any]: _snake_case = os.path.abspath(__lowerCamelCase ) logger.info(f'''Converting TensorFlow checkpoint from {tf_path}''' ) # Load weights from TF model _snake_case = tf.train.list_variables(__lowerCamelCase ) _snake_case = [] _snake_case = [] _snake_case = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") _snake_case = full_name.split('''/''' ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f'''Skipping non-model layer {full_name}''' ) continue if "optimizer" in full_name: logger.info(f'''Skipping optimization layer {full_name}''' ) continue if name[0] == "model": # ignore initial 'model' _snake_case = name[1:] # figure out how many levels deep the name is _snake_case = 0 for _name in name: if _name.startswith('''layer_with_weights''' ): depth += 1 else: break layer_depth.append(__lowerCamelCase ) # read data _snake_case = tf.train.load_variable(__lowerCamelCase , __lowerCamelCase ) names.append('''/'''.join(__lowerCamelCase ) ) arrays.append(__lowerCamelCase ) logger.info(f'''Read a total of {len(__lowerCamelCase ):,} layers''' ) # Sanity check if len(set(__lowerCamelCase ) ) != 1: raise ValueError(f'''Found layer names with different depths (layer depth {list(set(__lowerCamelCase ) )})''' ) _snake_case = list(set(__lowerCamelCase ) )[0] if layer_depth != 1: raise ValueError( '''The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP''' ''' heads.''' ) # convert layers logger.info('''Converting weights...''' ) for full_name, array in zip(__lowerCamelCase , __lowerCamelCase ): _snake_case = full_name.split('''/''' ) _snake_case = model _snake_case = [] for i, m_name in enumerate(__lowerCamelCase ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith('''layer_with_weights''' ): _snake_case = int(m_name.split('''-''' )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(['''embeddings''', '''LayerNorm'''] ) _snake_case = getattr(__lowerCamelCase , '''embeddings''' ) _snake_case = getattr(__lowerCamelCase , '''LayerNorm''' ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(['''encoder''', '''layer''', str(layer_num - 4 )] ) _snake_case = getattr(__lowerCamelCase , '''encoder''' ) _snake_case = getattr(__lowerCamelCase , '''layer''' ) _snake_case = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(['''pooler''', '''dense'''] ) _snake_case = getattr(__lowerCamelCase , '''pooler''' ) _snake_case = getattr(__lowerCamelCase , '''dense''' ) elif m_name == "embeddings": trace.append('''embeddings''' ) _snake_case = getattr(__lowerCamelCase , '''embeddings''' ) if layer_num == 0: trace.append('''word_embeddings''' ) _snake_case = getattr(__lowerCamelCase , '''word_embeddings''' ) elif layer_num == 1: trace.append('''position_embeddings''' ) _snake_case = getattr(__lowerCamelCase , '''position_embeddings''' ) elif layer_num == 2: trace.append('''token_type_embeddings''' ) _snake_case = getattr(__lowerCamelCase , '''token_type_embeddings''' ) else: raise ValueError(f'''Unknown embedding layer with name {full_name}''' ) trace.append('''weight''' ) _snake_case = getattr(__lowerCamelCase , '''weight''' ) elif m_name == "_attention_layer": # self-attention layer trace.extend(['''attention''', '''self'''] ) _snake_case = getattr(__lowerCamelCase , '''attention''' ) _snake_case = getattr(__lowerCamelCase , '''self''' ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(['''attention''', '''output''', '''LayerNorm'''] ) _snake_case = getattr(__lowerCamelCase , '''attention''' ) _snake_case = getattr(__lowerCamelCase , '''output''' ) _snake_case = getattr(__lowerCamelCase , '''LayerNorm''' ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(['''attention''', '''output''', '''dense'''] ) _snake_case = getattr(__lowerCamelCase , '''attention''' ) _snake_case = getattr(__lowerCamelCase , '''output''' ) _snake_case = getattr(__lowerCamelCase , '''dense''' ) elif m_name == "_output_dense": # output dense trace.extend(['''output''', '''dense'''] ) _snake_case = getattr(__lowerCamelCase , '''output''' ) _snake_case = getattr(__lowerCamelCase , '''dense''' ) elif m_name == "_output_layer_norm": # output dense trace.extend(['''output''', '''LayerNorm'''] ) _snake_case = getattr(__lowerCamelCase , '''output''' ) _snake_case = getattr(__lowerCamelCase , '''LayerNorm''' ) elif m_name == "_key_dense": # attention key trace.append('''key''' ) _snake_case = getattr(__lowerCamelCase , '''key''' ) elif m_name == "_query_dense": # attention query trace.append('''query''' ) _snake_case = getattr(__lowerCamelCase , '''query''' ) elif m_name == "_value_dense": # attention value trace.append('''value''' ) _snake_case = getattr(__lowerCamelCase , '''value''' ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(['''intermediate''', '''dense'''] ) _snake_case = getattr(__lowerCamelCase , '''intermediate''' ) _snake_case = getattr(__lowerCamelCase , '''dense''' ) elif m_name == "_output_layer_norm": # output layer norm trace.append('''output''' ) _snake_case = getattr(__lowerCamelCase , '''output''' ) # weights & biases elif m_name in ["bias", "beta"]: trace.append('''bias''' ) _snake_case = getattr(__lowerCamelCase , '''bias''' ) elif m_name in ["kernel", "gamma"]: trace.append('''weight''' ) _snake_case = getattr(__lowerCamelCase , '''weight''' ) else: logger.warning(f'''Ignored {m_name}''' ) # for certain layers reshape is necessary _snake_case = '''.'''.join(__lowerCamelCase ) if re.match(R'''(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)''' , __lowerCamelCase ) or re.match( R'''(\S+)\.attention\.output\.dense\.weight''' , __lowerCamelCase ): _snake_case = array.reshape(pointer.data.shape ) if "kernel" in full_name: _snake_case = array.transpose() if pointer.shape == array.shape: _snake_case = torch.from_numpy(__lowerCamelCase ) else: raise ValueError( f'''Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:''' f''' {array.shape}''' ) logger.info(f'''Successfully set variable {full_name} to PyTorch layer {trace}''' ) return model def _UpperCAmelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ) -> int: # Instantiate model logger.info(f'''Loading model based on config from {config_path}...''' ) _snake_case = BertConfig.from_json_file(__lowerCamelCase ) _snake_case = BertModel(__lowerCamelCase ) # Load weights from checkpoint logger.info(f'''Loading weights from checkpoint {tf_checkpoint_path}...''' ) load_tfa_weights_in_bert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save pytorch-model logger.info(f'''Saving PyTorch model to {pytorch_dump_path}...''' ) torch.save(model.state_dict() , __lowerCamelCase ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow 2.x checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model (must include filename).', ) UpperCAmelCase__ = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
430
1
'''simple docstring''' import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset A = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,UpperCamelCase : Optional[int] ) -> str: super().__init__() _lowercase : Optional[int] = torchvision.models.resnetaaa(pretrained=UpperCamelCase ) _lowercase : Optional[int] = list(model.children() )[:-2] _lowercase : Union[str, Any] = nn.Sequential(*UpperCamelCase ) _lowercase : Optional[Any] = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def _lowerCamelCase ( self : Dict ,UpperCamelCase : Optional[Any] ) -> Dict: # Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048 _lowercase : Union[str, Any] = self.pool(self.model(UpperCamelCase ) ) _lowercase : Union[str, Any] = torch.flatten(UpperCamelCase ,start_dim=2 ) _lowercase : Any = out.transpose(1 ,2 ).contiguous() return out # BxNx2048 class __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] ,UpperCamelCase : int ,UpperCamelCase : Tuple ,UpperCamelCase : Optional[int] ,UpperCamelCase : Dict ,UpperCamelCase : Optional[int] ) -> Optional[int]: _lowercase : Optional[int] = [json.loads(UpperCamelCase ) for l in open(UpperCamelCase )] _lowercase : Optional[int] = os.path.dirname(UpperCamelCase ) _lowercase : str = tokenizer _lowercase : Union[str, Any] = labels _lowercase : Optional[Any] = len(UpperCamelCase ) _lowercase : Union[str, Any] = max_seq_length _lowercase : Optional[int] = transforms def __len__( self : Optional[int] ) -> Optional[Any]: return len(self.data ) def __getitem__( self : Any ,UpperCamelCase : str ) -> List[str]: _lowercase : Tuple = torch.LongTensor(self.tokenizer.encode(self.data[index]['text'] ,add_special_tokens=UpperCamelCase ) ) _lowercase , _lowercase , _lowercase : Tuple = sentence[0], sentence[1:-1], sentence[-1] _lowercase : Dict = sentence[: self.max_seq_length] _lowercase : str = torch.zeros(self.n_classes ) _lowercase : Any = 1 _lowercase : Any = Image.open(os.path.join(self.data_dir ,self.data[index]['img'] ) ).convert('RGB' ) _lowercase : Optional[Any] = self.transforms(UpperCamelCase ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def _lowerCamelCase ( self : int ) -> Dict: _lowercase : Tuple = Counter() for row in self.data: label_freqs.update(row['label'] ) return label_freqs def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : int) -> str: '''simple docstring''' _lowercase : Optional[int] = [len(row['sentence']) for row in batch] _lowercase , _lowercase : int = len(lowerCAmelCase__), max(lowerCAmelCase__) _lowercase : Optional[int] = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ , dtype=torch.long) _lowercase : Any = torch.zeros(lowerCAmelCase__ , lowerCAmelCase__ , dtype=torch.long) for i_batch, (input_row, length) in enumerate(zip(lowerCAmelCase__ , lowerCAmelCase__)): _lowercase : List[str] = input_row['sentence'] _lowercase : Optional[Any] = 1 _lowercase : int = torch.stack([row['image'] for row in batch]) _lowercase : Any = torch.stack([row['label'] for row in batch]) _lowercase : int = torch.stack([row['image_start_token'] for row in batch]) _lowercase : Tuple = torch.stack([row['image_end_token'] for row in batch]) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def SCREAMING_SNAKE_CASE ( ) -> Any: '''simple docstring''' return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def SCREAMING_SNAKE_CASE ( ) -> str: '''simple docstring''' return transforms.Compose( [ transforms.Resize(2_56), transforms.CenterCrop(2_24), transforms.ToTensor(), transforms.Normalize( mean=[0.4_6_7_7_7_0_4_4, 0.4_4_5_3_1_4_2_9, 0.4_0_6_6_1_0_1_7] , std=[0.1_2_2_2_1_9_9_4, 0.1_2_1_4_5_8_3_5, 0.1_4_3_8_0_4_6_9] , ), ])
125
'''simple docstring''' import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int]=7) -> Any: '''simple docstring''' _lowercase : Any = None if token is not None: _lowercase : Tuple = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) _lowercase : int = '636036' _lowercase : str = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' _lowercase : Tuple = requests.get(lowerCAmelCase__ , headers=lowerCAmelCase__).json() return result["workflow_runs"] def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Tuple) -> Any: '''simple docstring''' _lowercase : Any = get_daily_ci_runs(lowerCAmelCase__) _lowercase : Union[str, Any] = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _lowercase : List[str] = workflow_run['id'] break return workflow_run_id def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any]) -> Optional[int]: '''simple docstring''' _lowercase : Any = get_last_daily_ci_runs(lowerCAmelCase__) if workflow_run_id is not None: _lowercase : Any = get_artifacts_links(worflow_run_id=lowerCAmelCase__ , token=lowerCAmelCase__) for artifact_name in artifact_names: if artifact_name in artifacts_links: _lowercase : str = artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase__ , artifact_url=lowerCAmelCase__ , output_dir=lowerCAmelCase__ , token=lowerCAmelCase__) def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str) -> List[Any]: '''simple docstring''' get_last_daily_ci_artifacts(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) _lowercase : List[Any] = {} for artifact_name in artifact_names: _lowercase : int = os.path.join(lowerCAmelCase__ , F'''{artifact_name}.zip''') if os.path.isfile(lowerCAmelCase__): _lowercase : Union[str, Any] = {} with zipfile.ZipFile(lowerCAmelCase__) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase__): # read the file with z.open(lowerCAmelCase__) as f: _lowercase : Optional[int] = f.read().decode('UTF-8') return results
125
1
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : Dict = logging.get_logger(__name__) A : List[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart A : str = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } A : Union[str, Any] = { "facebook/bart-base": 1_024, "facebook/bart-large": 1_024, "facebook/bart-large-mnli": 1_024, "facebook/bart-large-cnn": 1_024, "facebook/bart-large-xsum": 1_024, "yjernite/bart_eli5": 1_024, } @lru_cache() def snake_case__ ( ): """simple docstring""" UpperCamelCase__ = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) UpperCamelCase__ = bs[:] UpperCamelCase__ = 0 for b in range(2**8 ): if b not in bs: bs.append(__A ) cs.append(2**8 + n ) n += 1 UpperCamelCase__ = [chr(__A ) for n in cs] return dict(zip(__A , __A ) ) def snake_case__ ( _snake_case : Optional[Any] ): """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase__ = char return pairs class lowerCAmelCase ( __lowerCAmelCase ): '''simple docstring''' A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ['input_ids', 'attention_mask'] def __init__( self :Any , lowerCamelCase_ :List[Any] , lowerCamelCase_ :int , lowerCamelCase_ :Optional[Any]="replace" , lowerCamelCase_ :Tuple="<s>" , lowerCamelCase_ :Optional[int]="</s>" , lowerCamelCase_ :Any="</s>" , lowerCamelCase_ :Dict="<s>" , lowerCamelCase_ :str="<unk>" , lowerCamelCase_ :str="<pad>" , lowerCamelCase_ :List[str]="<mask>" , lowerCamelCase_ :Tuple=False , **lowerCamelCase_ :int , ) -> Dict: """simple docstring""" UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else bos_token UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else eos_token UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else sep_token UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else cls_token UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else unk_token UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase__ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token super().__init__( errors=_UpperCamelCase , bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , sep_token=_UpperCamelCase , cls_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , add_prefix_space=_UpperCamelCase , **_UpperCamelCase , ) with open(_UpperCamelCase , encoding="utf-8" ) as vocab_handle: UpperCamelCase__ = json.load(_UpperCamelCase ) UpperCamelCase__ = {v: k for k, v in self.encoder.items()} UpperCamelCase__ = errors # how to handle errors in decoding UpperCamelCase__ = bytes_to_unicode() UpperCamelCase__ = {v: k for k, v in self.byte_encoder.items()} with open(_UpperCamelCase , encoding="utf-8" ) as merges_handle: UpperCamelCase__ = merges_handle.read().split("\n" )[1:-1] UpperCamelCase__ = [tuple(merge.split() ) for merge in bpe_merges] UpperCamelCase__ = dict(zip(_UpperCamelCase , range(len(_UpperCamelCase ) ) ) ) UpperCamelCase__ = {} UpperCamelCase__ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCamelCase__ = re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def lowerCamelCase__ ( self :Tuple ) -> str: """simple docstring""" return len(self.encoder ) def lowerCamelCase__ ( self :List[Any] ) -> Tuple: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self :int , lowerCamelCase_ :str ) -> List[Any]: """simple docstring""" if token in self.cache: return self.cache[token] UpperCamelCase__ = tuple(_UpperCamelCase ) UpperCamelCase__ = get_pairs(_UpperCamelCase ) if not pairs: return token while True: UpperCamelCase__ = min(_UpperCamelCase , key=lambda lowerCamelCase_ : self.bpe_ranks.get(_UpperCamelCase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break UpperCamelCase__ = bigram UpperCamelCase__ = [] UpperCamelCase__ = 0 while i < len(_UpperCamelCase ): try: UpperCamelCase__ = word.index(_UpperCamelCase , _UpperCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCamelCase__ = j if word[i] == first and i < len(_UpperCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCamelCase__ = tuple(_UpperCamelCase ) UpperCamelCase__ = new_word if len(_UpperCamelCase ) == 1: break else: UpperCamelCase__ = get_pairs(_UpperCamelCase ) UpperCamelCase__ = """ """.join(_UpperCamelCase ) UpperCamelCase__ = word return word def lowerCamelCase__ ( self :Union[str, Any] , lowerCamelCase_ :Any ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = [] for token in re.findall(self.pat , _UpperCamelCase ): UpperCamelCase__ = """""".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_UpperCamelCase ).split(" " ) ) return bpe_tokens def lowerCamelCase__ ( self :List[str] , lowerCamelCase_ :Union[str, Any] ) -> List[Any]: """simple docstring""" return self.encoder.get(_UpperCamelCase , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self :Any , lowerCamelCase_ :List[Any] ) -> List[Any]: """simple docstring""" return self.decoder.get(_UpperCamelCase ) def lowerCamelCase__ ( self :Optional[int] , lowerCamelCase_ :Dict ) -> List[str]: """simple docstring""" UpperCamelCase__ = """""".join(_UpperCamelCase ) UpperCamelCase__ = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def lowerCamelCase__ ( self :str , lowerCamelCase_ :str , lowerCamelCase_ :Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_UpperCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( _UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join( _UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_UpperCamelCase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_UpperCamelCase , ensure_ascii=_UpperCamelCase ) + "\n" ) UpperCamelCase__ = 0 with open(_UpperCamelCase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda 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!" ) UpperCamelCase__ = token_index writer.write(" ".join(_UpperCamelCase ) + "\n" ) index += 1 return vocab_file, merge_file def lowerCamelCase__ ( self :List[str] , lowerCamelCase_ :List[int] , lowerCamelCase_ :Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self :Tuple , lowerCamelCase_ :List[int] , lowerCamelCase_ :Optional[List[int]] = None , lowerCamelCase_ :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1, 1] + ([0] * len(_UpperCamelCase )) + [1] def lowerCamelCase__ ( self :str , lowerCamelCase_ :List[int] , lowerCamelCase_ :Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCamelCase__ ( self :Tuple , lowerCamelCase_ :Tuple , lowerCamelCase_ :Optional[int]=False , **lowerCamelCase_ :str ) -> int: """simple docstring""" UpperCamelCase__ = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_UpperCamelCase ) > 0 and not text[0].isspace()): UpperCamelCase__ = """ """ + text return (text, kwargs)
715
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class lowerCAmelCase : '''simple docstring''' def __init__( self :List[str] , lowerCamelCase_ :List[Any] ) -> Dict: """simple docstring""" UpperCamelCase__ = data UpperCamelCase__ = [0X6745_2301, 0Xefcd_ab89, 0X98ba_dcfe, 0X1032_5476, 0Xc3d2_e1f0] @staticmethod def lowerCamelCase__ ( lowerCamelCase_ :Dict , lowerCamelCase_ :Tuple ) -> int: """simple docstring""" return ((n << b) | (n >> (3_2 - b))) & 0Xffff_ffff def lowerCamelCase__ ( self :List[str] ) -> str: """simple docstring""" UpperCamelCase__ = b"\x80" + b"\x00" * (6_3 - (len(self.data ) + 8) % 6_4) UpperCamelCase__ = self.data + padding + struct.pack(">Q" , 8 * len(self.data ) ) return padded_data def lowerCamelCase__ ( self :Optional[Any] ) -> Any: """simple docstring""" return [ self.padded_data[i : i + 6_4] for i in range(0 , len(self.padded_data ) , 6_4 ) ] def lowerCamelCase__ ( self :Optional[int] , lowerCamelCase_ :Dict ) -> Any: """simple docstring""" UpperCamelCase__ = list(struct.unpack(">16L" , lowerCamelCase_ ) ) + [0] * 6_4 for i in range(1_6 , 8_0 ): UpperCamelCase__ = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 1_4] ^ w[i - 1_6]) , 1 ) return w def lowerCamelCase__ ( self :Union[str, Any] ) -> List[str]: """simple docstring""" UpperCamelCase__ = self.padding() UpperCamelCase__ = self.split_blocks() for block in self.blocks: UpperCamelCase__ = self.expand_block(lowerCamelCase_ ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.h for i in range(0 , 8_0 ): if 0 <= i < 2_0: UpperCamelCase__ = (b & c) | ((~b) & d) UpperCamelCase__ = 0X5a82_7999 elif 2_0 <= i < 4_0: UpperCamelCase__ = b ^ c ^ d UpperCamelCase__ = 0X6ed9_eba1 elif 4_0 <= i < 6_0: UpperCamelCase__ = (b & c) | (b & d) | (c & d) UpperCamelCase__ = 0X8f1b_bcdc elif 6_0 <= i < 8_0: UpperCamelCase__ = b ^ c ^ d UpperCamelCase__ = 0Xca62_c1d6 UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = ( self.rotate(lowerCamelCase_ , 5 ) + f + e + k + expanded_block[i] & 0Xffff_ffff, a, self.rotate(lowerCamelCase_ , 3_0 ), c, d, ) UpperCamelCase__ = ( self.h[0] + a & 0Xffff_ffff, self.h[1] + b & 0Xffff_ffff, self.h[2] + c & 0Xffff_ffff, self.h[3] + d & 0Xffff_ffff, self.h[4] + e & 0Xffff_ffff, ) return ("{:08x}" * 5).format(*self.h ) def snake_case__ ( ): """simple docstring""" UpperCamelCase__ = b"Test String" assert SHAaHash(_snake_case ).final_hash() == hashlib.shaa(_snake_case ).hexdigest() # noqa: S324 def snake_case__ ( ): """simple docstring""" UpperCamelCase__ = argparse.ArgumentParser(description="Process some strings or files" ) parser.add_argument( "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument("--file" , dest="input_file" , help="Hash contents of a file" ) UpperCamelCase__ = parser.parse_args() UpperCamelCase__ = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = bytes(_snake_case , "utf-8" ) print(SHAaHash(_snake_case ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
304
0
'''simple docstring''' from typing import Any def _lowerCAmelCase ( __snake_case : str ) -> list[Any]: if not input_list: return [] __A : Union[str, Any] = [input_list.count(__SCREAMING_SNAKE_CASE ) for value in input_list] __A : List[Any] = max(__SCREAMING_SNAKE_CASE ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(__SCREAMING_SNAKE_CASE ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
8
'''simple docstring''' import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = "." # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) A_ = [ "Assert", "AssignVariableOp", "EmptyTensorList", "MergeV2Checkpoints", "ReadVariableOp", "ResourceGather", "RestoreV2", "SaveV2", "ShardedFilename", "StatefulPartitionedCall", "StaticRegexFullMatch", "VarHandleOp", ] def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case__ : str = SavedModel() snake_case__ : Union[str, Any] = [] with open(os.path.join(__SCREAMING_SNAKE_CASE , 'utils' , 'tf_ops' , 'onnx.json' ) ) as f: snake_case__ : Optional[Any] = json.load(__SCREAMING_SNAKE_CASE )['opsets'] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(__SCREAMING_SNAKE_CASE )] ) with open(__SCREAMING_SNAKE_CASE , 'rb' ) as f: saved_model.ParseFromString(f.read() ) snake_case__ : List[str] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want snake_case__ : Optional[int] = sorted(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(__SCREAMING_SNAKE_CASE ) if strict and len(__SCREAMING_SNAKE_CASE ) > 0: raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops ) elif len(__SCREAMING_SNAKE_CASE ) > 0: print(f"Found the following incompatible ops for the opset {opset}:" ) print(*__SCREAMING_SNAKE_CASE , sep='\n' ) else: print(f"The saved model {saved_model_path} can properly be converted with ONNX." ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") parser.add_argument( "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." ) parser.add_argument( "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." ) parser.add_argument( "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" ) A_ = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
270
0
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process UpperCamelCase_ = logging.getLogger(__name__) UpperCamelCase_ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) UpperCamelCase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _snake_case : '''simple docstring''' A__ : Optional[str] = field( default=__snake_case , metadata={ "help": ( "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." ) } , ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(__snake_case )} , ) A__ : Optional[str] = field( default=__snake_case , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) A__ : bool = field( default=__snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) A__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) A__ : bool = field( default=__snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def A__ ( self: Optional[int] ) -> Dict: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class _snake_case : '''simple docstring''' A__ : Optional[str] = field( default=__snake_case , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) A__ : Optional[str] = field(default=__snake_case , metadata={"help": "The input training data file (a text file)."} ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "An optional input train ref data file for whole word masking in Chinese."} , ) A__ : Optional[str] = field( default=__snake_case , metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."} , ) A__ : bool = field( default=__snake_case , metadata={"help": "Overwrite the cached training and evaluation sets"} ) A__ : Optional[int] = field( default=5 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) A__ : Optional[int] = field( default=__snake_case , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated. Default to the max input length of the model." ) } , ) A__ : Optional[int] = field( default=__snake_case , metadata={"help": "The number of processes to use for the preprocessing."} , ) A__ : float = field( default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} ) A__ : bool = field( default=__snake_case , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) def A__ ( self: int ) -> List[str]: if self.train_file is not None: UpperCAmelCase_ : Union[str, Any] = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: UpperCAmelCase_ : List[Any] = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase_ ( _a : Dict , _a : List[str] ): '''simple docstring''' with open(_a , """r""" , encoding="""utf-8""" ) as f: UpperCAmelCase_ : Optional[int] = [json.loads(_a ) for line in f.read().splitlines() if (len(_a ) > 0 and not line.isspace())] assert len(_a ) == len(_a ) UpperCAmelCase_ : Tuple = {c: dataset[c] for c in dataset.column_names} UpperCAmelCase_ : Optional[Any] = refs return Dataset.from_dict(_a ) def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = parser.parse_args_into_dataclasses() # Detecting last checkpoint. UpperCAmelCase_ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase_ : List[str] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , _a ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. UpperCAmelCase_ : Optional[Any] = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): UpperCAmelCase_ : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[:{data_args.validation_split_percentage}%]''' , ) UpperCAmelCase_ : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[{data_args.validation_split_percentage}%:]''' , ) else: UpperCAmelCase_ : int = {} if data_args.train_file is not None: UpperCAmelCase_ : List[Any] = data_args.train_file if data_args.validation_file is not None: UpperCAmelCase_ : Optional[int] = data_args.validation_file UpperCAmelCase_ : Tuple = data_args.train_file.split(""".""" )[-1] if extension == "txt": UpperCAmelCase_ : Optional[Any] = """text""" UpperCAmelCase_ : List[Any] = load_dataset(_a , data_files=_a ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCAmelCase_ : int = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: UpperCAmelCase_ : Dict = AutoConfig.from_pretrained(model_args.config_name , **_a ) elif model_args.model_name_or_path: UpperCAmelCase_ : Tuple = AutoConfig.from_pretrained(model_args.model_name_or_path , **_a ) else: UpperCAmelCase_ : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(F'''New config: {config}''' ) UpperCAmelCase_ : Tuple = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: UpperCAmelCase_ : Any = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_a ) elif model_args.model_name_or_path: UpperCAmelCase_ : Any = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_a ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: UpperCAmelCase_ : Tuple = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) UpperCAmelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_config(_a ) model.resize_token_embeddings(len(_a ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: UpperCAmelCase_ : Any = datasets["""train"""].column_names else: UpperCAmelCase_ : str = datasets["""validation"""].column_names UpperCAmelCase_ : Any = """text""" if """text""" in column_names else column_names[0] UpperCAmelCase_ : Union[str, Any] = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(_a : Union[str, Any] ): # Remove empty lines UpperCAmelCase_ : int = [line for line in examples["""text"""] if len(_a ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] , padding=_a , truncation=_a , max_length=data_args.max_seq_length ) UpperCAmelCase_ : str = datasets.map( _a , batched=_a , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: UpperCAmelCase_ : Union[str, Any] = add_chinese_references(tokenized_datasets["""train"""] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: UpperCAmelCase_ : Tuple = add_chinese_references( tokenized_datasets["""validation"""] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer UpperCAmelCase_ : int = data_args.train_ref_file or data_args.validation_ref_file if has_ref: UpperCAmelCase_ : List[Any] = False # Data collator # This one will take care of randomly masking the tokens. UpperCAmelCase_ : Tuple = DataCollatorForWholeWordMask(tokenizer=_a , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCAmelCase_ : Tuple = Trainer( model=_a , args=_a , train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None , eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None , tokenizer=_a , data_collator=_a , ) # Training if training_args.do_train: if last_checkpoint is not None: UpperCAmelCase_ : Optional[Any] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): UpperCAmelCase_ : Dict = model_args.model_name_or_path else: UpperCAmelCase_ : str = None UpperCAmelCase_ : Union[str, Any] = trainer.train(resume_from_checkpoint=_a ) trainer.save_model() # Saves the tokenizer too for easy upload UpperCAmelCase_ : List[str] = os.path.join(training_args.output_dir , """train_results.txt""" ) if trainer.is_world_process_zero(): with open(_a , """w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F''' {key} = {value}''' ) writer.write(F'''{key} = {value}\n''' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , """trainer_state.json""" ) ) # Evaluation UpperCAmelCase_ : Any = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCAmelCase_ : int = trainer.evaluate() UpperCAmelCase_ : Optional[int] = math.exp(eval_output["""eval_loss"""] ) UpperCAmelCase_ : Dict = perplexity UpperCAmelCase_ : List[str] = os.path.join(training_args.output_dir , """eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(_a , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(F''' {key} = {value}''' ) writer.write(F'''{key} = {value}\n''' ) return results def lowerCamelCase_ ( _a : List[str] ): '''simple docstring''' main() if __name__ == "__main__": main()
322
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _snake_case : '''simple docstring''' def __init__( self: int ,lowerCamelCase_: Optional[int] ,lowerCamelCase_: Optional[Any]=13 ,lowerCamelCase_: List[str]=7 ,lowerCamelCase_: Optional[int]=True ,lowerCamelCase_: int=True ,lowerCamelCase_: Dict=False ,lowerCamelCase_: Dict=True ,lowerCamelCase_: Optional[Any]=99 ,lowerCamelCase_: Union[str, Any]=32 ,lowerCamelCase_: str=5 ,lowerCamelCase_: Optional[int]=4 ,lowerCamelCase_: Union[str, Any]=37 ,lowerCamelCase_: Optional[int]="gelu" ,lowerCamelCase_: Tuple=0.1 ,lowerCamelCase_: Any=0.1 ,lowerCamelCase_: List[str]=512 ,lowerCamelCase_: Tuple=16 ,lowerCamelCase_: Dict=2 ,lowerCamelCase_: int=0.0_2 ,lowerCamelCase_: Optional[int]=3 ,lowerCamelCase_: Tuple=4 ,lowerCamelCase_: Optional[int]=None ,) -> List[Any]: UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Dict = batch_size UpperCAmelCase_ : Dict = seq_length UpperCAmelCase_ : Tuple = is_training UpperCAmelCase_ : int = use_input_mask UpperCAmelCase_ : Tuple = use_token_type_ids UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : List[str] = hidden_size UpperCAmelCase_ : List[str] = num_hidden_layers UpperCAmelCase_ : Optional[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Tuple = hidden_act UpperCAmelCase_ : Union[str, Any] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Tuple = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Optional[Any] = type_sequence_label_size UpperCAmelCase_ : Dict = initializer_range UpperCAmelCase_ : List[Any] = num_labels UpperCAmelCase_ : Dict = num_choices UpperCAmelCase_ : int = scope def A__ ( self: Optional[int] ) -> int: UpperCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) UpperCAmelCase_ : Tuple = None if self.use_input_mask: UpperCAmelCase_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : Tuple = None if self.use_token_type_ids: UpperCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) UpperCAmelCase_ : Union[str, Any] = None UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : int = None if self.use_labels: UpperCAmelCase_ : str = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) UpperCAmelCase_ : Any = ids_tensor([self.batch_size] ,self.num_choices ) UpperCAmelCase_ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A__ ( self: Dict ) -> int: return LlamaConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=lowerCamelCase_ ,initializer_range=self.initializer_range ,) def A__ ( self: Dict ,lowerCamelCase_: Any ,lowerCamelCase_: Optional[Any] ,lowerCamelCase_: Tuple ,lowerCamelCase_: List[Any] ,lowerCamelCase_: Optional[Any] ,lowerCamelCase_: List[Any] ,lowerCamelCase_: List[str] ) -> List[Any]: UpperCAmelCase_ : Dict = LlamaModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : Union[str, Any] = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ) UpperCAmelCase_ : int = model(lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def A__ ( self: List[str] ,lowerCamelCase_: Dict ,lowerCamelCase_: int ,lowerCamelCase_: Union[str, Any] ,lowerCamelCase_: int ,lowerCamelCase_: int ,lowerCamelCase_: Union[str, Any] ,lowerCamelCase_: int ,lowerCamelCase_: List[str] ,lowerCamelCase_: List[str] ,) -> Dict: UpperCAmelCase_ : Union[str, Any] = True UpperCAmelCase_ : Union[str, Any] = LlamaModel(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : str = model( lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,encoder_hidden_states=lowerCamelCase_ ,encoder_attention_mask=lowerCamelCase_ ,) UpperCAmelCase_ : Dict = model( lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,encoder_hidden_states=lowerCamelCase_ ,) UpperCAmelCase_ : Dict = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def A__ ( self: List[Any] ,lowerCamelCase_: Union[str, Any] ,lowerCamelCase_: Dict ,lowerCamelCase_: List[str] ,lowerCamelCase_: str ,lowerCamelCase_: List[str] ,lowerCamelCase_: Optional[Any] ,lowerCamelCase_: Optional[int] ,lowerCamelCase_: Optional[int] ,lowerCamelCase_: int ,) -> Union[str, Any]: UpperCAmelCase_ : Dict = LlamaForCausalLM(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : Union[str, Any] = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def A__ ( self: Dict ,lowerCamelCase_: Tuple ,lowerCamelCase_: int ,lowerCamelCase_: Tuple ,lowerCamelCase_: Tuple ,lowerCamelCase_: List[str] ,lowerCamelCase_: Optional[int] ,lowerCamelCase_: int ,lowerCamelCase_: List[Any] ,lowerCamelCase_: str ,) -> Tuple: UpperCAmelCase_ : Union[str, Any] = True UpperCAmelCase_ : Optional[Any] = True UpperCAmelCase_ : Optional[int] = LlamaForCausalLM(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() # first forward pass UpperCAmelCase_ : Any = model( lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,encoder_hidden_states=lowerCamelCase_ ,encoder_attention_mask=lowerCamelCase_ ,use_cache=lowerCamelCase_ ,) UpperCAmelCase_ : Any = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Dict = ids_tensor((self.batch_size, 3) ,config.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and UpperCAmelCase_ : Union[str, Any] = torch.cat([input_ids, next_tokens] ,dim=-1 ) UpperCAmelCase_ : Tuple = torch.cat([input_mask, next_mask] ,dim=-1 ) UpperCAmelCase_ : Union[str, Any] = model( lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,encoder_hidden_states=lowerCamelCase_ ,encoder_attention_mask=lowerCamelCase_ ,output_hidden_states=lowerCamelCase_ ,)["""hidden_states"""][0] UpperCAmelCase_ : List[Any] = model( lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,encoder_hidden_states=lowerCamelCase_ ,encoder_attention_mask=lowerCamelCase_ ,past_key_values=lowerCamelCase_ ,output_hidden_states=lowerCamelCase_ ,)["""hidden_states"""][0] # select random slice UpperCAmelCase_ : Union[str, Any] = ids_tensor((1,) ,output_from_past.shape[-1] ).item() UpperCAmelCase_ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-3 ) ) def A__ ( self: Optional[Any] ) -> str: UpperCAmelCase_ : Any = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _snake_case ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' A__ : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () A__ : List[str] = (LlamaForCausalLM,) if is_torch_available() else () A__ : str = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) A__ : Dict = False A__ : str = False def A__ ( self: List[str] ) -> Any: UpperCAmelCase_ : Any = LlamaModelTester(self ) UpperCAmelCase_ : Union[str, Any] = ConfigTester(self ,config_class=lowerCamelCase_ ,hidden_size=37 ) def A__ ( self: Optional[int] ) -> Dict: self.config_tester.run_common_tests() def A__ ( self: Any ) -> Tuple: UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def A__ ( self: str ) -> Union[str, Any]: UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Optional[int] = type self.model_tester.create_and_check_model(*lowerCamelCase_ ) def A__ ( self: List[str] ) -> Optional[Any]: UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : int = 3 UpperCAmelCase_ : Tuple = input_dict["""input_ids"""] UpperCAmelCase_ : Any = input_ids.ne(1 ).to(lowerCamelCase_ ) UpperCAmelCase_ : Any = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : List[str] = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : List[Any] = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def A__ ( self: Any ) -> Optional[int]: UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Any = 3 UpperCAmelCase_ : Dict = """single_label_classification""" UpperCAmelCase_ : List[str] = input_dict["""input_ids"""] UpperCAmelCase_ : Any = input_ids.ne(1 ).to(lowerCamelCase_ ) UpperCAmelCase_ : Optional[Any] = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Union[str, Any] = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : List[Any] = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def A__ ( self: Optional[int] ) -> List[str]: UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Optional[Any] = 3 UpperCAmelCase_ : Optional[Any] = """multi_label_classification""" UpperCAmelCase_ : Optional[Any] = input_dict["""input_ids"""] UpperCAmelCase_ : Tuple = input_ids.ne(1 ).to(lowerCamelCase_ ) UpperCAmelCase_ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : List[Any] = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase_ : int = model(lowerCamelCase_ ,attention_mask=lowerCamelCase_ ,labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def A__ ( self: Any ) -> Optional[int]: pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def A__ ( self: Optional[int] ,lowerCamelCase_: int ) -> Union[str, Any]: UpperCAmelCase_ , UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Optional[int] = ids_tensor([1, 10] ,config.vocab_size ) UpperCAmelCase_ : Tuple = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCAmelCase_ : Tuple = LlamaModel(lowerCamelCase_ ) original_model.to(lowerCamelCase_ ) original_model.eval() UpperCAmelCase_ : Any = original_model(lowerCamelCase_ ).last_hidden_state UpperCAmelCase_ : List[Any] = original_model(lowerCamelCase_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCAmelCase_ : Optional[Any] = {"""type""": scaling_type, """factor""": 1_0.0} UpperCAmelCase_ : List[str] = LlamaModel(lowerCamelCase_ ) scaled_model.to(lowerCamelCase_ ) scaled_model.eval() UpperCAmelCase_ : int = scaled_model(lowerCamelCase_ ).last_hidden_state UpperCAmelCase_ : Union[str, Any] = scaled_model(lowerCamelCase_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-5 ) ) @require_torch class _snake_case ( unittest.TestCase ): '''simple docstring''' @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def A__ ( self: str ) -> Union[str, Any]: UpperCAmelCase_ : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] UpperCAmelCase_ : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" ,device_map="""auto""" ) UpperCAmelCase_ : Optional[int] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 UpperCAmelCase_ : Optional[Any] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) ,lowerCamelCase_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCAmelCase_ : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,lowerCamelCase_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def A__ ( self: Optional[int] ) -> Union[str, Any]: UpperCAmelCase_ : Optional[Any] = [1, 306, 4658, 278, 6593, 310, 2834, 338] UpperCAmelCase_ : List[Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" ,device_map="""auto""" ) UpperCAmelCase_ : Optional[int] = model(torch.tensor(lowerCamelCase_ ) ) # Expected mean on dim = -1 UpperCAmelCase_ : int = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) ,lowerCamelCase_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCAmelCase_ : List[Any] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,lowerCamelCase_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def A__ ( self: Tuple ) -> Dict: UpperCAmelCase_ : Optional[Any] = [1, 306, 4658, 278, 6593, 310, 2834, 338] UpperCAmelCase_ : Union[str, Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ,device_map="""auto""" ) UpperCAmelCase_ : str = model(torch.tensor(lowerCamelCase_ ) ) # Expected mean on dim = -1 UpperCAmelCase_ : Optional[int] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) ,lowerCamelCase_ ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off UpperCAmelCase_ : Tuple = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,lowerCamelCase_ ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def A__ ( self: Any ) -> List[Any]: UpperCAmelCase_ : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] UpperCAmelCase_ : str = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" ,device_map="""auto""" ) UpperCAmelCase_ : int = model(torch.tensor(lowerCamelCase_ ) ) UpperCAmelCase_ : int = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,lowerCamelCase_ ,atol=1e-2 ,rtol=1e-2 ) # fmt: off UpperCAmelCase_ : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,lowerCamelCase_ ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("""Model is curently gated""" ) @slow def A__ ( self: Any ) -> List[str]: UpperCAmelCase_ : Dict = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" UpperCAmelCase_ : Optional[int] = """Simply put, the theory of relativity states that """ UpperCAmelCase_ : Dict = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) UpperCAmelCase_ : List[str] = tokenizer.encode(lowerCamelCase_ ,return_tensors="""pt""" ) UpperCAmelCase_ : List[Any] = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" ,device_map="""sequential""" ,use_safetensors=lowerCamelCase_ ) # greedy generation outputs UpperCAmelCase_ : str = model.generate(lowerCamelCase_ ,max_new_tokens=64 ,top_p=lowerCamelCase_ ,temperature=1 ,do_sample=lowerCamelCase_ ) UpperCAmelCase_ : Tuple = tokenizer.decode(generated_ids[0] ,skip_special_tokens=lowerCamelCase_ ) self.assertEqual(lowerCamelCase_ ,lowerCamelCase_ )
322
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
605
from __future__ import annotations def SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" if len(UpperCAmelCase__ ) == 0: return array _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = min(UpperCAmelCase__ ), max(UpperCAmelCase__ ) # Compute the variables _SCREAMING_SNAKE_CASE = _max - _min + 1 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _SCREAMING_SNAKE_CASE = i - _min _SCREAMING_SNAKE_CASE = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _SCREAMING_SNAKE_CASE = 0 for i in range(UpperCAmelCase__ ): while holes_repeat[i] > 0: _SCREAMING_SNAKE_CASE = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() snake_case : Dict = input('Enter numbers separated by comma:\n') snake_case : List[Any] = [int(x) for x in user_input.split(',')] print(pigeon_sort(unsorted))
605
1
from __future__ import annotations from math import pi, sqrt def _UpperCamelCase (a__ :float , a__ :float ): """simple docstring""" if inductance <= 0: raise ValueError("""Inductance cannot be 0 or negative""" ) elif capacitance <= 0: raise ValueError("""Capacitance cannot be 0 or negative""" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
548
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) UpperCamelCase__ = parser.parse_args() UpperCamelCase__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) UpperCamelCase__ = CLIPImageProcessor() UpperCamelCase__ = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") UpperCamelCase__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
548
1
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger lowerCamelCase = get_logger(__name__) class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[Any] , _lowerCAmelCase : Optional[str] = None): '''simple docstring''' __lowercase =( os.path.join(_lowerCAmelCase , config.EXTRACTED_DATASETS_DIR) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __lowercase =Extractor def __lowerCamelCase ( self : List[Any] , _lowerCAmelCase : str): '''simple docstring''' from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __lowercase =os.path.abspath(_lowerCAmelCase) return os.path.join(self.extract_dir , hash_url_to_filename(_lowerCAmelCase)) def __lowerCamelCase ( self : Dict , _lowerCAmelCase : str , _lowerCAmelCase : bool): '''simple docstring''' return force_extract or ( not os.path.isfile(_lowerCAmelCase) and not (os.path.isdir(_lowerCAmelCase) and os.listdir(_lowerCAmelCase)) ) def __lowerCamelCase ( self : str , _lowerCAmelCase : str , _lowerCAmelCase : bool = False): '''simple docstring''' __lowercase =self.extractor.infer_extractor_format(_lowerCAmelCase) if not extractor_format: return input_path __lowercase =self._get_output_path(_lowerCAmelCase) if self._do_extract(_lowerCAmelCase , _lowerCAmelCase): self.extractor.extract(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase) return output_path class _UpperCamelCase ( A ): '''simple docstring''' @classmethod @abstractmethod def __lowerCamelCase ( cls : List[Any] , _lowerCAmelCase : Union[Path, str] , **_lowerCAmelCase : Union[str, Any]): '''simple docstring''' ... @staticmethod @abstractmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' ... class _UpperCamelCase ( A , A ): '''simple docstring''' lowerCAmelCase__ = [] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : int): '''simple docstring''' with open(_lowerCAmelCase , 'rb') as f: return f.read(_lowerCAmelCase) @classmethod def __lowerCamelCase ( cls : Union[str, Any] , _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : bytes = b""): '''simple docstring''' if not magic_number: __lowercase =max(len(_lowerCAmelCase) for cls_magic_number in cls.magic_numbers) try: __lowercase =cls.read_magic_number(_lowerCAmelCase , _lowerCAmelCase) except OSError: return False return any(magic_number.startswith(_lowerCAmelCase) for cls_magic_number in cls.magic_numbers) class _UpperCamelCase ( A ): '''simple docstring''' @classmethod def __lowerCamelCase ( cls : List[str] , _lowerCAmelCase : Union[Path, str] , **_lowerCAmelCase : Union[str, Any]): '''simple docstring''' return tarfile.is_tarfile(_lowerCAmelCase) @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any]): '''simple docstring''' def resolved(_lowerCAmelCase : str) -> str: return os.path.realpath(os.path.abspath(_lowerCAmelCase)) def badpath(_lowerCAmelCase : str , _lowerCAmelCase : str) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(_lowerCAmelCase , _lowerCAmelCase)).startswith(_lowerCAmelCase) def badlink(_lowerCAmelCase : Tuple , _lowerCAmelCase : str) -> bool: # Links are interpreted relative to the directory containing the link __lowercase =resolved(os.path.join(_lowerCAmelCase , os.path.dirname(info.name))) return badpath(info.linkname , base=_lowerCAmelCase) __lowercase =resolved(_lowerCAmelCase) for finfo in members: if badpath(finfo.name , _lowerCAmelCase): logger.error(f"""Extraction of {finfo.name} is blocked (illegal path)""") elif finfo.issym() and badlink(_lowerCAmelCase , _lowerCAmelCase): logger.error(f"""Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}""") elif finfo.islnk() and badlink(_lowerCAmelCase , _lowerCAmelCase): logger.error(f"""Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}""") else: yield finfo @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase) __lowercase =tarfile.open(_lowerCAmelCase) tar_file.extractall(_lowerCAmelCase , members=TarExtractor.safemembers(_lowerCAmelCase , _lowerCAmelCase)) tar_file.close() class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\x1F\x8B"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' with gzip.open(_lowerCAmelCase , 'rb') as gzip_file: with open(_lowerCAmelCase , 'wb') as extracted_file: shutil.copyfileobj(_lowerCAmelCase , _lowerCAmelCase) class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [ B"""PK\x03\x04""", B"""PK\x05\x06""", # empty archive B"""PK\x07\x08""", # spanned archive ] @classmethod def __lowerCamelCase ( cls : Optional[int] , _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : bytes = b""): '''simple docstring''' if super().is_extractable(_lowerCAmelCase , magic_number=_lowerCAmelCase): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(_lowerCAmelCase , 'rb') as fp: __lowercase =_EndRecData(_lowerCAmelCase) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET]) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __lowercase =fp.read(_lowerCAmelCase) # CD is where we expect it to be if len(_lowerCAmelCase) == sizeCentralDir: __lowercase =struct.unpack(_lowerCAmelCase , _lowerCAmelCase) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase) with zipfile.ZipFile(_lowerCAmelCase , 'r') as zip_file: zip_file.extractall(_lowerCAmelCase) zip_file.close() class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\xFD\x37\x7A\x58\x5A\x00"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' with lzma.open(_lowerCAmelCase) as compressed_file: with open(_lowerCAmelCase , 'wb') as extracted_file: shutil.copyfileobj(_lowerCAmelCase , _lowerCAmelCase) class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""] # RAR_ID # RAR5_ID @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' if not config.RARFILE_AVAILABLE: raise ImportError('Please pip install rarfile') import rarfile os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase) __lowercase =rarfile.RarFile(_lowerCAmelCase) rf.extractall(_lowerCAmelCase) rf.close() class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\x28\xb5\x2F\xFD"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' if not config.ZSTANDARD_AVAILABLE: raise ImportError('Please pip install zstandard') import zstandard as zstd __lowercase =zstd.ZstdDecompressor() with open(_lowerCAmelCase , 'rb') as ifh, open(_lowerCAmelCase , 'wb') as ofh: dctx.copy_stream(_lowerCAmelCase , _lowerCAmelCase) class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\x42\x5A\x68"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' with bza.open(_lowerCAmelCase , 'rb') as compressed_file: with open(_lowerCAmelCase , 'wb') as extracted_file: shutil.copyfileobj(_lowerCAmelCase , _lowerCAmelCase) class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\x37\x7A\xBC\xAF\x27\x1C"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' if not config.PY7ZR_AVAILABLE: raise ImportError('Please pip install py7zr') import pyazr os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase) with pyazr.SevenZipFile(_lowerCAmelCase , 'r') as archive: archive.extractall(_lowerCAmelCase) class _UpperCamelCase ( A ): '''simple docstring''' lowerCAmelCase__ = [B"""\x04\x22\x4D\x18"""] @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str]): '''simple docstring''' if not config.LZ4_AVAILABLE: raise ImportError('Please pip install lz4') import lza.frame with lza.frame.open(_lowerCAmelCase , 'rb') as compressed_file: with open(_lowerCAmelCase , 'wb') as extracted_file: shutil.copyfileobj(_lowerCAmelCase , _lowerCAmelCase) class _UpperCamelCase : '''simple docstring''' lowerCAmelCase__ = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def __lowerCamelCase ( cls : Dict): '''simple docstring''' return max( len(_lowerCAmelCase) for extractor in cls.extractors.values() if issubclass(_lowerCAmelCase , _lowerCAmelCase) for extractor_magic_number in extractor.magic_numbers) @staticmethod def __lowerCamelCase ( _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : int): '''simple docstring''' try: return MagicNumberBaseExtractor.read_magic_number(_lowerCAmelCase , magic_number_length=_lowerCAmelCase) except OSError: return b"" @classmethod def __lowerCamelCase ( cls : int , _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : bool = False): '''simple docstring''' warnings.warn( 'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'infer_extractor_format\' instead.' , category=_lowerCAmelCase , ) __lowercase =cls.infer_extractor_format(_lowerCAmelCase) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def __lowerCamelCase ( cls : Optional[Any] , _lowerCAmelCase : Union[Path, str]): # <Added version="2.4.0"/> '''simple docstring''' __lowercase =cls._get_magic_number_max_length() __lowercase =cls._read_magic_number(_lowerCAmelCase , _lowerCAmelCase) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(_lowerCAmelCase , magic_number=_lowerCAmelCase): return extractor_format @classmethod def __lowerCamelCase ( cls : List[str] , _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Union[Path, str] , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[BaseExtractor] = "deprecated" , ): '''simple docstring''' os.makedirs(os.path.dirname(_lowerCAmelCase) , exist_ok=_lowerCAmelCase) # Prevent parallel extractions __lowercase =str(Path(_lowerCAmelCase).with_suffix('.lock')) with FileLock(_lowerCAmelCase): shutil.rmtree(_lowerCAmelCase , ignore_errors=_lowerCAmelCase) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(_lowerCAmelCase , _lowerCAmelCase): # passed as positional arg warnings.warn( 'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'extractor_format\' instead.' , category=_lowerCAmelCase , ) __lowercase =extractor if extractor != 'deprecated' else extractor_format else: __lowercase =cls.extractors[extractor_format] return extractor.extract(_lowerCAmelCase , _lowerCAmelCase) else: warnings.warn( 'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an ' 'exception in 3.0.0.' , category=_lowerCAmelCase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(_lowerCAmelCase): return extractor.extract(_lowerCAmelCase , _lowerCAmelCase)
474
'''simple docstring''' def _A ( _lowerCAmelCase = 2_000_000 ): """simple docstring""" __lowercase =[0 for i in range(n + 1 )] __lowercase =1 __lowercase =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , _lowerCAmelCase ): __lowercase =1 __lowercase =0 for i in range(_lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"{solution() = }")
474
1
"""simple docstring""" def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase = False ): if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_3170_4406_4679_8873_8596_1981 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.' ) # array bounds provided by analysis lowerCamelCase__ : Dict = [ 2047, 137_3653, 2532_6001, 32_1503_1751, 2_1523_0289_8747, 3_4747_4966_0383, 341_5500_7172_8321, 1, 382_5123_0565_4641_3051, 1, 1, 3186_6585_7834_0311_5116_7461, 3_3170_4406_4679_8873_8596_1981, ] lowerCamelCase__ : str = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(_lowerCamelCase , 1 ): if n < _p: # then we have our last prime to check lowerCamelCase__ : Any = primes[:idx] break lowerCamelCase__ : int = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase__ : Optional[Any] = False for r in range(_lowerCamelCase ): lowerCamelCase__ : Any = pow(_lowerCamelCase , d * 2**r , _lowerCamelCase ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase__ : Dict = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def lowerCamelCase_ ( ): assert not miller_rabin(561 ) assert miller_rabin(563 ) # 2047 assert not miller_rabin(83_8201 ) assert miller_rabin(83_8207 ) # 1_373_653 assert not miller_rabin(1731_6001 ) assert miller_rabin(1731_6017 ) # 25_326_001 assert not miller_rabin(30_7838_6641 ) assert miller_rabin(30_7838_6653 ) # 3_215_031_751 assert not miller_rabin(1_7130_4557_4801 ) assert miller_rabin(1_7130_4557_4819 ) # 2_152_302_898_747 assert not miller_rabin(2_7797_9972_8307 ) assert miller_rabin(2_7797_9972_8327 ) # 3_474_749_660_383 assert not miller_rabin(113_8500_2390_9441 ) assert miller_rabin(113_8500_2390_9527 ) # 341_550_071_728_321 assert not miller_rabin(127_5041_0188_4880_4351 ) assert miller_rabin(127_5041_0188_4880_4391 ) # 3_825_123_056_546_413_051 assert not miller_rabin(796_6646_4458_5077_8779_1867 ) assert miller_rabin(796_6646_4458_5077_8779_1951 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(5528_4067_7446_6478_9766_0333 ) assert miller_rabin(5528_4067_7446_6478_9766_0359 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
715
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 A_ : int = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 1_28, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "exponential_decay_length_penalty": (5, 1.01), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class a_ ( unittest.TestCase ): '''simple docstring''' @classmethod def a__ (cls ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = TOKEN HfFolder.save_token(lowerCamelCase_ ) @classmethod def a__ (cls ): '''simple docstring''' try: delete_repo(token=cls._token, repo_id='test-config' ) except HTTPError: pass try: delete_repo(token=cls._token, repo_id='valid_org/test-config-org' ) except HTTPError: pass try: delete_repo(token=cls._token, repo_id='test-dynamic-config' ) except HTTPError: pass def a__ (self ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = BertConfig( vocab_size=9_9, hidden_size=3_2, num_hidden_layers=5, num_attention_heads=4, intermediate_size=3_7 ) config.push_to_hub('test-config', use_auth_token=self._token ) lowerCamelCase__ : Optional[int] = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) # Reset repo delete_repo(token=self._token, repo_id='test-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase_, repo_id='test-config', push_to_hub=lowerCamelCase_, use_auth_token=self._token ) lowerCamelCase__ : List[str] = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = BertConfig( vocab_size=9_9, hidden_size=3_2, num_hidden_layers=5, num_attention_heads=4, intermediate_size=3_7 ) config.push_to_hub('valid_org/test-config-org', use_auth_token=self._token ) lowerCamelCase__ : Union[str, Any] = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) # Reset repo delete_repo(token=self._token, repo_id='valid_org/test-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowerCamelCase_, repo_id='valid_org/test-config-org', push_to_hub=lowerCamelCase_, use_auth_token=self._token ) lowerCamelCase__ : str = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) def a__ (self ): '''simple docstring''' CustomConfig.register_for_auto_class() lowerCamelCase__ : Optional[int] = CustomConfig(attribute=4_2 ) config.push_to_hub('test-dynamic-config', use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map, {'AutoConfig': 'custom_configuration.CustomConfig'} ) lowerCamelCase__ : List[str] = AutoConfig.from_pretrained(f'''{USER}/test-dynamic-config''', trust_remote_code=lowerCamelCase_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__, 'CustomConfig' ) self.assertEqual(new_config.attribute, 4_2 ) class a_ ( unittest.TestCase ): '''simple docstring''' def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated lowerCamelCase__ : Tuple = c.n_embd + 1 # int lowerCamelCase__ : Union[str, Any] = c.resid_pdrop + 1.0 # float lowerCamelCase__ : List[Any] = not c.scale_attn_weights # bool lowerCamelCase__ : List[Any] = c.summary_type + 'foo' # str c.update_from_string( f'''n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}''' ) self.assertEqual(lowerCamelCase_, c.n_embd, 'mismatch for key: n_embd' ) self.assertEqual(lowerCamelCase_, c.resid_pdrop, 'mismatch for key: resid_pdrop' ) self.assertEqual(lowerCamelCase_, c.scale_attn_weights, 'mismatch for key: scale_attn_weights' ) self.assertEqual(lowerCamelCase_, c.summary_type, 'mismatch for key: summary_type' ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : List[str] = PretrainedConfig() lowerCamelCase__ : Optional[Any] = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( lowerCamelCase_, ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'] ) lowerCamelCase__ : Any = [key for key, value in config_common_kwargs.items() if value == getattr(lowerCamelCase_, lowerCamelCase_ )] if len(lowerCamelCase_ ) > 0: raise ValueError( 'The following keys are set with the default values in' ' `test_configuration_common.config_common_kwargs` pick another value for them:' f''' {', '.join(lowerCamelCase_ )}.''' ) def a__ (self ): '''simple docstring''' with self.assertRaises(lowerCamelCase_ ): # config is in subfolder, the following should not work without specifying the subfolder lowerCamelCase__ : Union[str, Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' ) lowerCamelCase__ : int = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder', subfolder='bert' ) self.assertIsNotNone(lowerCamelCase_ ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = mock.Mock() lowerCamelCase__ : List[str] = 5_0_0 lowerCamelCase__ : Any = {} lowerCamelCase__ : int = HTTPError lowerCamelCase__ : Optional[Any] = {} # Download this model to make sure it's in the cache. lowerCamelCase__ : Any = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request', return_value=lowerCamelCase_ ) as mock_head: lowerCamelCase__ : List[str] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() def a__ (self ): '''simple docstring''' lowerCamelCase__ : Dict = BertConfig.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json' ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : Tuple = AutoConfig.from_pretrained('bert-base-cased' ) lowerCamelCase__ : str = ['config.4.0.0.json'] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(lowerCamelCase_ ) lowerCamelCase__ : Optional[Any] = 2 json.dump(configuration.to_dict(), open(os.path.join(lowerCamelCase_, 'config.4.0.0.json' ), 'w' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 lowerCamelCase__ : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(new_configuration.hidden_size, 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 lowerCamelCase__ : str = ['config.42.0.0.json'] lowerCamelCase__ : Union[str, Any] = 7_6_8 configuration.save_pretrained(lowerCamelCase_ ) shutil.move(os.path.join(lowerCamelCase_, 'config.4.0.0.json' ), os.path.join(lowerCamelCase_, 'config.42.0.0.json' ) ) lowerCamelCase__ : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(new_configuration.hidden_size, 7_6_8 ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : Optional[int] = 'hf-internal-testing/test-two-configs' import transformers as new_transformers lowerCamelCase__ : Optional[int] = 'v4.0.0' lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = new_transformers.models.auto.AutoConfig.from_pretrained( lowerCamelCase_, return_unused_kwargs=lowerCamelCase_ ) self.assertEqual(new_configuration.hidden_size, 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(lowerCamelCase_, {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers lowerCamelCase__ : Dict = 'v3.0.0' lowerCamelCase__ : List[str] = old_transformers.models.auto.AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(old_configuration.hidden_size, 7_6_8 )
696
0
# Function to print upper half of diamond (pyramid) def __snake_case ( lowerCAmelCase_ ) -> List[Any]: for i in range(0 , lowerCAmelCase_ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def __snake_case ( lowerCAmelCase_ ) -> Tuple: for i in range(lowerCAmelCase_ , 0 , -1 ): for _ in range(lowerCAmelCase_ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def __snake_case ( lowerCAmelCase_ ) -> Tuple: if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(lowerCAmelCase_ ) # upper half reverse_floyd(lowerCAmelCase_ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") _A : str = 1 while K: _A : str = int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) _A : Dict = int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
100
import numpy as np def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> np.ndarray: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> np.ndarray: return vector * sigmoid(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
33
0
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a__ ( __A , unittest.TestCase ): """simple docstring""" __UpperCamelCase : List[str] = MgpstrTokenizer __UpperCamelCase : Any = False __UpperCamelCase : Optional[int] = {} __UpperCamelCase : Union[str, Any] = False def _snake_case (self ): super().setUp() # fmt: off __lowerCAmelCase = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on __lowerCAmelCase = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) ) __lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '''\n''' ) def _snake_case (self , **__lowercase ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def _snake_case (self , __lowercase ): __lowerCAmelCase = '''tester''' __lowerCAmelCase = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def _snake_case (self ): pass def _snake_case (self ): __lowerCAmelCase = self.get_tokenizers(do_lower_case=_SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __lowerCAmelCase = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) __lowerCAmelCase = tokenizer.encode([special_token] , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1 ) __lowerCAmelCase = tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertTrue(special_token not in decoded ) def _snake_case (self ): __lowerCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __lowerCAmelCase , __lowerCAmelCase = self.get_input_output_texts(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ) self.assertNotEqual(len(_SCREAMING_SNAKE_CASE ) , 0 ) __lowerCAmelCase = tokenizer.decode(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , _SCREAMING_SNAKE_CASE ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def _snake_case (self ): pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def _snake_case (self ): pass
713
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _UpperCAmelCase : str = { """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: _UpperCAmelCase : Union[str, Any] = [ """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 _UpperCAmelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
474
0
'''simple docstring''' import math def snake_case_ (UpperCamelCase : 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 snake_case_ (UpperCamelCase : int = 1_0001 ): '''simple docstring''' try: _a = int(UpperCamelCase ) except (TypeError, ValueError): raise TypeError('''Parameter nth must be int or castable to int.''' ) from None if nth <= 0: raise ValueError('''Parameter nth must be greater than or equal to one.''' ) _a = [] _a = 2 while len(UpperCamelCase ) < nth: if is_prime(UpperCamelCase ): primes.append(UpperCamelCase ) num += 1 else: num += 1 return primes[len(UpperCamelCase ) - 1] if __name__ == "__main__": print(F'''{solution() = }''')
22
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Tuple: # Load configuration defined in the metadata file with open(_lowerCamelCase ) as metadata_file: _UpperCAmelCase =json.load(_lowerCamelCase ) _UpperCAmelCase =LukeConfig(use_entity_aware_attention=_lowerCamelCase , **metadata["model_config"] ) # Load in the weights from the checkpoint_path _UpperCAmelCase =torch.load(_lowerCamelCase , map_location="cpu" )["module"] # Load the entity vocab file _UpperCAmelCase =load_original_entity_vocab(_lowerCamelCase ) # add an entry for [MASK2] _UpperCAmelCase =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 _UpperCAmelCase =XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks _UpperCAmelCase =AddedToken("<ent>" , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) _UpperCAmelCase =AddedToken("<ent2>" , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(_lowerCamelCase ) with open(os.path.join(_lowerCamelCase , "tokenizer_config.json" ) , "r" ) as f: _UpperCAmelCase =json.load(_lowerCamelCase ) _UpperCAmelCase ="MLukeTokenizer" with open(os.path.join(_lowerCamelCase , "tokenizer_config.json" ) , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) with open(os.path.join(_lowerCamelCase , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase ) # Initialize the embeddings of the special tokens _UpperCAmelCase =tokenizer.convert_tokens_to_ids(["@"] )[0] _UpperCAmelCase =tokenizer.convert_tokens_to_ids(["#"] )[0] _UpperCAmelCase =state_dict["embeddings.word_embeddings.weight"] _UpperCAmelCase =word_emb[ent_init_index].unsqueeze(0 ) _UpperCAmelCase =word_emb[enta_init_index].unsqueeze(0 ) _UpperCAmelCase =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: _UpperCAmelCase =state_dict[bias_name] _UpperCAmelCase =decoder_bias[ent_init_index].unsqueeze(0 ) _UpperCAmelCase =decoder_bias[enta_init_index].unsqueeze(0 ) _UpperCAmelCase =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _UpperCAmelCase =F"encoder.layer.{layer_index}.attention.self." _UpperCAmelCase =state_dict[prefix + matrix_name] _UpperCAmelCase =state_dict[prefix + matrix_name] _UpperCAmelCase =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _UpperCAmelCase =state_dict["entity_embeddings.entity_embeddings.weight"] _UpperCAmelCase =entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCAmelCase =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' _UpperCAmelCase =state_dict["entity_predictions.bias"] _UpperCAmelCase =entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCAmelCase =torch.cat([entity_prediction_bias, entity_mask_bias] ) _UpperCAmelCase =LukeForMaskedLM(config=_lowerCamelCase ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) _UpperCAmelCase =OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): _UpperCAmelCase =state_dict[key] else: _UpperCAmelCase =state_dict[key] _UpperCAmelCase , _UpperCAmelCase =model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) if set(_lowerCamelCase ) != {"luke.embeddings.position_ids"}: raise ValueError(F"Unexpected unexpected_keys: {unexpected_keys}" ) if set(_lowerCamelCase ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase , task="entity_classification" ) _UpperCAmelCase ="ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." _UpperCAmelCase =(0, 9) _UpperCAmelCase =tokenizer(_lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) _UpperCAmelCase =model(**_lowerCamelCase ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase =torch.Size((1, 33, 768) ) _UpperCAmelCase =torch.tensor([[0.0_892, 0.0_596, -0.2_819], [0.0_134, 0.1_199, 0.0_573], [-0.0_169, 0.0_927, 0.0_644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase =torch.Size((1, 1, 768) ) _UpperCAmelCase =torch.tensor([[-0.1_482, 0.0_609, 0.0_322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" F" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=1e-4 ): raise ValueError # Verify masked word/entity prediction _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase ) _UpperCAmelCase ="Tokyo is the capital of <mask>." _UpperCAmelCase =(24, 30) _UpperCAmelCase =tokenizer(_lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) _UpperCAmelCase =model(**_lowerCamelCase ) _UpperCAmelCase =encoding["input_ids"][0].tolist() _UpperCAmelCase =input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) _UpperCAmelCase =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(_lowerCamelCase ) _UpperCAmelCase =outputs.entity_logits[0][0].argmax().item() _UpperCAmelCase =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(_lowerCamelCase ) ) model.save_pretrained(_lowerCamelCase ) def lowerCamelCase__ ( _lowerCamelCase ) ->str: _UpperCAmelCase =["[MASK]", "[PAD]", "[UNK]"] _UpperCAmelCase =[json.loads(_lowerCamelCase ) for line in open(_lowerCamelCase )] _UpperCAmelCase ={} for entry in data: _UpperCAmelCase =entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: _UpperCAmelCase =entity_id break _UpperCAmelCase =F"{language}:{entity_name}" _UpperCAmelCase =entity_id return new_mapping if __name__ == "__main__": snake_case__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) snake_case__ : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
408
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "microsoft/cvt-13": "https://huggingface.co/microsoft/cvt-13/resolve/main/config.json", # See all Cvt models at https://huggingface.co/models?filter=cvt } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'cvt' def __init__( self : Optional[int] ,snake_case : List[Any]=3 ,snake_case : Tuple=[7, 3, 3] ,snake_case : Tuple=[4, 2, 2] ,snake_case : List[str]=[2, 1, 1] ,snake_case : Dict=[64, 192, 384] ,snake_case : int=[1, 3, 6] ,snake_case : Optional[Any]=[1, 2, 10] ,snake_case : str=[4.0, 4.0, 4.0] ,snake_case : Dict=[0.0, 0.0, 0.0] ,snake_case : str=[0.0, 0.0, 0.0] ,snake_case : List[Any]=[0.0, 0.0, 0.1] ,snake_case : List[str]=[True, True, True] ,snake_case : Union[str, Any]=[False, False, True] ,snake_case : Optional[int]=["dw_bn", "dw_bn", "dw_bn"] ,snake_case : List[Any]=[3, 3, 3] ,snake_case : Optional[int]=[1, 1, 1] ,snake_case : Union[str, Any]=[2, 2, 2] ,snake_case : Dict=[1, 1, 1] ,snake_case : List[Any]=[1, 1, 1] ,snake_case : str=0.02 ,snake_case : Dict=1e-12 ,**snake_case : int ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =patch_sizes SCREAMING_SNAKE_CASE =patch_stride SCREAMING_SNAKE_CASE =patch_padding SCREAMING_SNAKE_CASE =embed_dim SCREAMING_SNAKE_CASE =num_heads SCREAMING_SNAKE_CASE =depth SCREAMING_SNAKE_CASE =mlp_ratio SCREAMING_SNAKE_CASE =attention_drop_rate SCREAMING_SNAKE_CASE =drop_rate SCREAMING_SNAKE_CASE =drop_path_rate SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =qkv_projection_method SCREAMING_SNAKE_CASE =kernel_qkv SCREAMING_SNAKE_CASE =padding_kv SCREAMING_SNAKE_CASE =stride_kv SCREAMING_SNAKE_CASE =padding_q SCREAMING_SNAKE_CASE =stride_q SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps
252
from ...processing_utils import ProcessorMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['image_processor', 'feature_extractor'] __UpperCAmelCase = 'TvltImageProcessor' __UpperCAmelCase = 'TvltFeatureExtractor' def __init__( self : Optional[int] ,snake_case : List[str] ,snake_case : Dict ): super().__init__(image_processor=snake_case ,feature_extractor=snake_case ) SCREAMING_SNAKE_CASE =image_processor SCREAMING_SNAKE_CASE =feature_extractor def __call__( self : Dict ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]=None ,snake_case : List[Any]=None ,snake_case : int=None ,snake_case : List[Any]=False ,snake_case : Optional[int]=False ,*snake_case : int ,**snake_case : str ,): if images is None and audio is None: raise ValueError('You need to specify either an `images` or `audio` input to process.' ) SCREAMING_SNAKE_CASE =None if images is not None: SCREAMING_SNAKE_CASE =self.image_processor(snake_case ,mask_pixel=snake_case ,*snake_case ,**snake_case ) if images_mixed is not None: SCREAMING_SNAKE_CASE =self.image_processor(snake_case ,is_mixed=snake_case ,*snake_case ,**snake_case ) if audio is not None: SCREAMING_SNAKE_CASE =self.feature_extractor( snake_case ,*snake_case ,sampling_rate=snake_case ,mask_audio=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE ={} if audio is not None: output_dict.update(snake_case ) if images is not None: output_dict.update(snake_case ) if images_mixed_dict is not None: output_dict.update(snake_case ) return output_dict @property def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.image_processor.model_input_names SCREAMING_SNAKE_CASE =self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
252
1
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase_ ( _lowercase ): _lowercase : str = (DDPMParallelScheduler,) def lowerCAmelCase_ ( self : List[Any] , **__A : int ): __A : int = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**__A ) return config def lowerCAmelCase_ ( self : List[str] ): for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=__A ) def lowerCAmelCase_ ( self : int ): for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ): self.check_over_configs(beta_start=__A , beta_end=__A ) def lowerCAmelCase_ ( self : Any ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__A ) def lowerCAmelCase_ ( self : Any ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=__A ) def lowerCAmelCase_ ( self : List[Any] ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def lowerCAmelCase_ ( self : int ): self.check_over_configs(thresholding=__A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , ) def lowerCAmelCase_ ( self : int ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def lowerCAmelCase_ ( self : int ): for t in [0, 500, 999]: self.check_over_forward(time_step=__A ) def lowerCAmelCase_ ( self : Union[str, Any] ): __A : str = self.scheduler_classes[0] __A : Tuple = self.get_scheduler_config() __A : int = scheduler_class(**__A ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0_9_7_9 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.0_2 ) ) < 1e-5 def lowerCAmelCase_ ( self : Optional[int] ): __A : int = self.scheduler_classes[0] __A : Optional[int] = self.get_scheduler_config() __A : List[Any] = scheduler_class(**__A ) __A : Any = len(__A ) __A : Tuple = self.dummy_model() __A : Union[str, Any] = self.dummy_sample_deter __A : List[Any] = self.dummy_sample_deter + 0.1 __A : Optional[Any] = self.dummy_sample_deter - 0.1 __A : Dict = samplea.shape[0] __A : Optional[int] = torch.stack([samplea, samplea, samplea] , dim=0 ) __A : Dict = torch.arange(__A )[0:3, None].repeat(1 , __A ) __A : Optional[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __A : Dict = scheduler.batch_step_no_noise(__A , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) __A : List[str] = torch.sum(torch.abs(__A ) ) __A : List[str] = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_1_5_3.1_8_3_3 ) < 1e-2 assert abs(result_mean.item() - 0.5_0_0_5 ) < 1e-3 def lowerCAmelCase_ ( self : Optional[int] ): __A : int = self.scheduler_classes[0] __A : int = self.get_scheduler_config() __A : Dict = scheduler_class(**__A ) __A : Optional[Any] = len(__A ) __A : Tuple = self.dummy_model() __A : Optional[Any] = self.dummy_sample_deter __A : List[str] = torch.manual_seed(0 ) for t in reversed(range(__A ) ): # 1. predict noise residual __A : str = model(__A , __A ) # 2. predict previous mean of sample x_t-1 __A : List[str] = scheduler.step(__A , __A , __A , generator=__A ).prev_sample __A : Union[str, Any] = pred_prev_sample __A : List[Any] = torch.sum(torch.abs(__A ) ) __A : Union[str, Any] = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 2_5_8.9_6_0_6 ) < 1e-2 assert abs(result_mean.item() - 0.3_3_7_2 ) < 1e-3 def lowerCAmelCase_ ( self : int ): __A : int = self.scheduler_classes[0] __A : int = self.get_scheduler_config(prediction_type="""v_prediction""" ) __A : int = scheduler_class(**__A ) __A : Dict = len(__A ) __A : Any = self.dummy_model() __A : str = self.dummy_sample_deter __A : Union[str, Any] = torch.manual_seed(0 ) for t in reversed(range(__A ) ): # 1. predict noise residual __A : Optional[Any] = model(__A , __A ) # 2. predict previous mean of sample x_t-1 __A : Tuple = scheduler.step(__A , __A , __A , generator=__A ).prev_sample __A : Dict = pred_prev_sample __A : Union[str, Any] = torch.sum(torch.abs(__A ) ) __A : Union[str, Any] = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 2_0_2.0_2_9_6 ) < 1e-2 assert abs(result_mean.item() - 0.2_6_3_1 ) < 1e-3 def lowerCAmelCase_ ( self : Any ): __A : List[str] = self.scheduler_classes[0] __A : Any = self.get_scheduler_config() __A : Optional[Any] = scheduler_class(**__A ) __A : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=__A ) __A : List[Any] = scheduler.timesteps for i, timestep in enumerate(__A ): if i == len(__A ) - 1: __A : List[str] = -1 else: __A : int = timesteps[i + 1] __A : Any = scheduler.previous_timestep(__A ) __A : Any = prev_t.item() self.assertEqual(__A , __A ) def lowerCAmelCase_ ( self : Any ): __A : str = self.scheduler_classes[0] __A : int = self.get_scheduler_config() __A : Optional[int] = scheduler_class(**__A ) __A : Any = [100, 87, 50, 51, 0] with self.assertRaises(__A , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=__A ) def lowerCAmelCase_ ( self : Any ): __A : List[str] = self.scheduler_classes[0] __A : Dict = self.get_scheduler_config() __A : Tuple = scheduler_class(**__A ) __A : Tuple = [100, 87, 50, 1, 0] __A : Union[str, Any] = len(__A ) with self.assertRaises(__A , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=__A , timesteps=__A ) def lowerCAmelCase_ ( self : Any ): __A : Tuple = self.scheduler_classes[0] __A : Optional[int] = self.get_scheduler_config() __A : Dict = scheduler_class(**__A ) __A : List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( __A , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=__A )
17
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=2 , lowerCAmelCase_=8 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=99 , lowerCAmelCase_=16 , lowerCAmelCase_=5 , lowerCAmelCase_=2 , lowerCAmelCase_=36 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=5_12 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=3 , lowerCAmelCase_=4 , lowerCAmelCase_=None , ): """simple docstring""" _snake_case = parent _snake_case = batch_size _snake_case = seq_length _snake_case = is_training _snake_case = use_input_mask _snake_case = use_token_type_ids _snake_case = use_labels _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = num_choices _snake_case = scope def lowerCamelCase ( self ): """simple docstring""" _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_input_mask: _snake_case = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case = None if self.use_token_type_ids: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _snake_case = None _snake_case = None _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case = ids_tensor([self.batch_size] , self.num_choices ) _snake_case = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase ( self ): """simple docstring""" return MraConfig( 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 , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.get_config() _snake_case = 3_00 return config def lowerCamelCase ( self ): """simple docstring""" ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) = self.prepare_config_and_inputs() _snake_case = True _snake_case = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = MraModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): """simple docstring""" _snake_case = True _snake_case = MraModel(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , encoder_attention_mask=lowerCAmelCase_ , ) _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , ) _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = MraForMaskedLM(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = MraForQuestionAnswering(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , start_positions=lowerCAmelCase_ , end_positions=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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_labels _snake_case = MraForSequenceClassification(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_labels _snake_case = MraForTokenClassification(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_choices _snake_case = MraForMultipleChoice(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) = config_and_inputs _snake_case = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCAmelCase ( _lowerCamelCase , unittest.TestCase ): __lowercase = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __lowercase = False __lowercase = False __lowercase = False __lowercase = False __lowercase = () def lowerCamelCase ( self ): """simple docstring""" _snake_case = MraModelTester(self ) _snake_case = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 ) def lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case = type self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase_ ) @slow def lowerCamelCase ( self ): """simple docstring""" for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = MraModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) @unittest.skip(reason='MRA does not output attentions' ) def lowerCamelCase ( self ): """simple docstring""" return @require_torch class __UpperCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = MraModel.from_pretrained('uw-madison/mra-base-512-4' ) _snake_case = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): _snake_case = model(lowerCAmelCase_ )[0] _snake_case = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , lowerCAmelCase_ ) _snake_case = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) ) @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' ) _snake_case = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): _snake_case = model(lowerCAmelCase_ )[0] _snake_case = 5_02_65 _snake_case = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , lowerCAmelCase_ ) _snake_case = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) ) @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' ) _snake_case = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): _snake_case = model(lowerCAmelCase_ )[0] _snake_case = 5_02_65 _snake_case = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , lowerCAmelCase_ ) _snake_case = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) )
495
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None ) ->Union[str, Any]: if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(lowerCAmelCase_ , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class __lowercase : UpperCamelCase = OPTConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self : Dict , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any]=1_3 , __lowerCamelCase : int=7 , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : Any=9_9 , __lowerCamelCase : Optional[int]=1_6 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Optional[int]=4 , __lowerCamelCase : str=4 , __lowerCamelCase : Optional[int]="gelu" , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : Any=2_0 , __lowerCamelCase : Dict=2 , __lowerCamelCase : Dict=1 , __lowerCamelCase : List[Any]=0 , __lowerCamelCase : Union[str, Any]=1_6 , __lowerCamelCase : Union[str, Any]=1_6 , ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training 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 = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = embed_dim UpperCAmelCase = word_embed_proj_dim UpperCAmelCase = False def _lowercase ( self : Any ) -> str: """simple docstring""" UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__lowerCamelCase , **self.config_updates , ) UpperCAmelCase = prepare_opt_inputs_dict(__lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def _lowercase ( self : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Dict ) -> int: """simple docstring""" UpperCAmelCase = TFOPTModel(config=__lowerCamelCase ) UpperCAmelCase = inputs_dict["""input_ids"""] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict["""attention_mask"""][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(__lowerCamelCase , attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) UpperCAmelCase , UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] UpperCAmelCase = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1e-3 ) @require_tf class __lowercase ( __snake_case , __snake_case , unittest.TestCase ): UpperCamelCase = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () UpperCamelCase = (TFOPTForCausalLM,) if is_tf_available() else () UpperCamelCase = ( {'''feature-extraction''': TFOPTModel, '''text-generation''': TFOPTForCausalLM} if is_tf_available() else {} ) UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = 10 def _lowercase ( self : str ) -> Dict: """simple docstring""" UpperCAmelCase = TFOPTModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=__lowerCamelCase ) def _lowercase ( self : Dict ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Union[str, Any] ) -> Any: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) def _lowercase ( self : List[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(__lowerCamelCase : int , __lowerCamelCase : Tuple ): if hasattr(__lowerCamelCase , """weight""" ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(__lowerCamelCase , """weight""" ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]: # build the embeddings UpperCAmelCase = model_class(config=__lowerCamelCase ) UpperCAmelCase = _get_word_embedding_weight(__lowerCamelCase , model.get_input_embeddings() ) UpperCAmelCase = _get_word_embedding_weight(__lowerCamelCase , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(__lowerCamelCase ) UpperCAmelCase = _get_word_embedding_weight(__lowerCamelCase , model.get_input_embeddings() ) UpperCAmelCase = _get_word_embedding_weight(__lowerCamelCase , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. UpperCAmelCase = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , __lowerCamelCase ) # check that weights remain the same after resizing UpperCAmelCase = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: UpperCAmelCase = False self.assertTrue(__lowerCamelCase ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , __lowerCamelCase ) UpperCAmelCase = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: UpperCAmelCase = False self.assertTrue(__lowerCamelCase ) def _UpperCamelCase ( lowerCAmelCase_ ) ->Optional[Any]: return tf.constant(lowerCAmelCase_ , dtype=tf.intaa ) @require_tf class __lowercase ( unittest.TestCase ): UpperCamelCase = 99 def _lowercase ( self : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = tf.ones((4, 1) , dtype=tf.intaa ) * 2 UpperCAmelCase = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) UpperCAmelCase = input_ids.shape[0] UpperCAmelCase = OPTConfig( vocab_size=self.vocab_size , hidden_size=2_4 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class __lowercase ( unittest.TestCase ): @slow def _lowercase ( self : Tuple ) -> Dict: """simple docstring""" UpperCAmelCase = TFOPTModel.from_pretrained("""facebook/opt-350m""" ) UpperCAmelCase = _long_tensor([[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]] ) UpperCAmelCase = tf.not_equal(__lowerCamelCase , model.config.pad_token_id ) with tf.GradientTape(): UpperCAmelCase = model(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase ).last_hidden_state UpperCAmelCase = (1, 1_1, 5_1_2) self.assertEqual(output.shape , __lowerCamelCase ) UpperCAmelCase = tf.constant( [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , __lowerCamelCase , atol=4e-3 ) ) UpperCAmelCase = tf.function(__lowerCamelCase , jit_compile=__lowerCamelCase ) UpperCAmelCase = xla_generate(__lowerCamelCase , __lowerCamelCase )[0] self.assertTrue(np.allclose(output[:, :3, :3] , __lowerCamelCase , atol=4e-2 ) ) @require_tf @slow class __lowercase ( unittest.TestCase ): def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" super().setUp() UpperCAmelCase = """facebook/opt-350m""" def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase = TFOPTForCausalLM.from_pretrained(self.path_model ) UpperCAmelCase = GPTaTokenizer.from_pretrained(self.path_model ) UpperCAmelCase = [ """Today is a beautiful day and I want to""", """In the city of""", """Paris is the capital of France and""", """Computers and mobile phones have taken""", ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False UpperCAmelCase = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) UpperCAmelCase = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) UpperCAmelCase = tf.constant( [ [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670], [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822], [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703], [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477], ] ) self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-4 ) ) UpperCAmelCase = tf.function(__lowerCamelCase , jit_compile=__lowerCamelCase ) UpperCAmelCase = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-4 ) ) @require_tf @slow class __lowercase ( unittest.TestCase ): @property def _lowercase ( self : Any ) -> str: """simple docstring""" return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def _lowercase ( self : List[str] ) -> Tuple: """simple docstring""" UpperCAmelCase = """facebook/opt-125m""" UpperCAmelCase = [ """Today is a beautiful day and I want to""", """In the city of New York, the city""", """Paris is the capital of France and the capital""", """Computers and mobile phones have taken over the""", ] UpperCAmelCase = [] UpperCAmelCase = GPTaTokenizer.from_pretrained(__lowerCamelCase ) UpperCAmelCase = TFOPTForCausalLM.from_pretrained(__lowerCamelCase ) for prompt in self.prompts: UpperCAmelCase = tokenizer(__lowerCamelCase , return_tensors="""tf""" ).input_ids UpperCAmelCase = model.generate(__lowerCamelCase , max_length=1_0 ) UpperCAmelCase = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) predicted_outputs += generated_string self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _lowercase ( self : Tuple ) -> str: """simple docstring""" UpperCAmelCase = """facebook/opt-350m""" UpperCAmelCase = GPTaTokenizer.from_pretrained(__lowerCamelCase ) UpperCAmelCase = TFOPTForCausalLM.from_pretrained(__lowerCamelCase ) UpperCAmelCase = """left""" # use different length sentences to test batching UpperCAmelCase = [ """Hello, my dog is a little""", """Today, I""", ] UpperCAmelCase = tokenizer(__lowerCamelCase , return_tensors="""tf""" , padding=__lowerCamelCase ) UpperCAmelCase = inputs["""input_ids"""] UpperCAmelCase = model.generate(input_ids=__lowerCamelCase , attention_mask=inputs["""attention_mask"""] ) UpperCAmelCase = tokenizer(sentences[0] , return_tensors="""tf""" ).input_ids UpperCAmelCase = model.generate(input_ids=__lowerCamelCase ) UpperCAmelCase = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs["""attention_mask"""][-1] , tf.intaa ) ) UpperCAmelCase = tokenizer(sentences[1] , return_tensors="""tf""" ).input_ids UpperCAmelCase = model.generate(input_ids=__lowerCamelCase , max_length=model.config.max_length - num_paddings ) UpperCAmelCase = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) UpperCAmelCase = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__lowerCamelCase ) UpperCAmelCase = tokenizer.decode(output_padded[0] , skip_special_tokens=__lowerCamelCase ) UpperCAmelCase = [ """Hello, my dog is a little bit of a dork.\nI'm a little bit""", """Today, I was in the middle of a conversation with a friend about the""", ] self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) self.assertListEqual(__lowerCamelCase , [non_padded_sentence, padded_sentence] ) def _lowercase ( self : str ) -> Tuple: """simple docstring""" UpperCAmelCase = """facebook/opt-350m""" UpperCAmelCase = [ """Today is a beautiful day and I want to""", """In the city of San Francisco, the city""", """Paris is the capital of France and the capital""", """Computers and mobile phones have taken over the""", ] UpperCAmelCase = [] UpperCAmelCase = GPTaTokenizer.from_pretrained(__lowerCamelCase ) UpperCAmelCase = TFOPTForCausalLM.from_pretrained(__lowerCamelCase ) for prompt in self.prompts: UpperCAmelCase = tokenizer(__lowerCamelCase , return_tensors="""tf""" ).input_ids UpperCAmelCase = model.generate(__lowerCamelCase , max_length=1_0 ) UpperCAmelCase = tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) predicted_outputs += generated_string self.assertListEqual(__lowerCamelCase , __lowerCamelCase )
627
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __a = """\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } """ __a = """\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. """ __a = """ Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for 'record': list of question-answer dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'prediction_text': the predicted answer text - for 'multirc': list of question-answer dictionaries with the following keys: - 'idx': index of the question-answer pair as specified by the dataset - 'prediction': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for 'record': list of question-answers dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'answers': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for 'record': - 'exact_match': Exact match between answer and gold answer - 'f1': F1 score - for 'multirc': - 'exact_match': Exact match between answer and gold answer - 'f1_m': Per-question macro-F1 score - 'f1_a': Average F1 score over all answers - for 'axb': 'matthews_correlation': Matthew Correlation - for 'cb': - 'accuracy': Accuracy - 'f1': F1 score - for all others: - 'accuracy': Accuracy Examples: >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'cb') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'record') >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}] >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc') >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'axb') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) ->List[str]: return float((preds == labels).mean() ) def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="binary" ) ->Union[str, Any]: UpperCAmelCase = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase = float(fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ , average=lowerCAmelCase_ ) ) return { "accuracy": acc, "f1": fa, } def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) ->List[Any]: UpperCAmelCase = {} for id_pred, label in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase = F"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCAmelCase = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCAmelCase = [(pred, label)] UpperCAmelCase , UpperCAmelCase = [], [] for question, preds_labels in question_map.items(): UpperCAmelCase , UpperCAmelCase = zip(*lowerCAmelCase_ ) UpperCAmelCase = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ , average="""macro""" ) fas.append(lowerCAmelCase_ ) UpperCAmelCase = int(sum(pred == label for pred, label in preds_labels ) == len(lowerCAmelCase_ ) ) ems.append(lowerCAmelCase_ ) UpperCAmelCase = float(sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) ) UpperCAmelCase = sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) UpperCAmelCase = float(fa_score(y_true=lowerCAmelCase_ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowercase ( datasets.Metric ): def _lowercase ( self : int ) -> Any: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _lowercase ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCAmelCase = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCAmelCase = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
627
1
def _a ( SCREAMING_SNAKE_CASE__ : int = 1_00_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
663
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowerCamelCase (unittest.TestCase ): """simple docstring""" @require_torch def A_ ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" ) SCREAMING_SNAKE_CASE__ : int = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : int = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> Dict: """simple docstring""" pass @slow @require_torch def A_ ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ : List[str] = load_dataset("ashraq/esc50" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dataset["train"]["audio"][-1]["array"] SCREAMING_SNAKE_CASE__ : Optional[Any] = audio_classifier(_UpperCAmelCase, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) SCREAMING_SNAKE_CASE__ : Any = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(_UpperCAmelCase ), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF" ) def A_ ( self : str ) -> List[str]: """simple docstring""" pass
663
1
class UpperCamelCase : def __init__(self , __UpperCamelCase = "" , __UpperCamelCase = False ) -> None: # Mapping from the first character of the prefix of the node UpperCamelCase_ : dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word UpperCamelCase_ : Optional[int] = is_leaf UpperCamelCase_ : List[str] = prefix def A_ (self , __UpperCamelCase ) -> tuple[str, str, str]: UpperCamelCase_ : Tuple = 0 for q, w in zip(self.prefix , __UpperCamelCase ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def A_ (self , __UpperCamelCase ) -> None: for word in words: self.insert(__UpperCamelCase ) def A_ (self , __UpperCamelCase ) -> None: # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: UpperCamelCase_ : int = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: UpperCamelCase_ : List[Any] = RadixNode(prefix=__UpperCamelCase , is_leaf=__UpperCamelCase ) else: UpperCamelCase_ : Dict = self.nodes[word[0]] UpperCamelCase_,UpperCamelCase_,UpperCamelCase_ : List[Any] = incoming_node.match( __UpperCamelCase ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(__UpperCamelCase ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: UpperCamelCase_ : int = remaining_prefix UpperCamelCase_ : Tuple = self.nodes[matching_string[0]] UpperCamelCase_ : str = RadixNode(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase_ : Dict = aux_node if remaining_word == "": UpperCamelCase_ : Optional[int] = True else: self.nodes[matching_string[0]].insert(__UpperCamelCase ) def A_ (self , __UpperCamelCase ) -> bool: UpperCamelCase_ : str = self.nodes.get(word[0] , __UpperCamelCase ) if not incoming_node: return False else: UpperCamelCase_,UpperCamelCase_,UpperCamelCase_ : Union[str, Any] = incoming_node.match( __UpperCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(__UpperCamelCase ) def A_ (self , __UpperCamelCase ) -> bool: UpperCamelCase_ : Optional[int] = self.nodes.get(word[0] , __UpperCamelCase ) if not incoming_node: return False else: UpperCamelCase_,UpperCamelCase_,UpperCamelCase_ : List[str] = incoming_node.match( __UpperCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(__UpperCamelCase ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: UpperCamelCase_ : Union[str, Any] = list(self.nodes.values() )[0] UpperCamelCase_ : Any = merging_node.is_leaf self.prefix += merging_node.prefix UpperCamelCase_ : Union[str, Any] = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: UpperCamelCase_ : Any = False # If there is 1 edge, we merge it with its child else: UpperCamelCase_ : str = list(incoming_node.nodes.values() )[0] UpperCamelCase_ : Tuple = merging_node.is_leaf incoming_node.prefix += merging_node.prefix UpperCamelCase_ : Tuple = merging_node.nodes return True def A_ (self , __UpperCamelCase = 0 ) -> None: if self.prefix != "": print("""-""" * height , self.prefix , """ (leaf)""" if self.is_leaf else """""" ) for value in self.nodes.values(): value.print_tree(height + 1 ) def lowerCAmelCase_ ( ): UpperCamelCase_ : Optional[int] = """banana bananas bandana band apple all beast""".split() UpperCamelCase_ : Union[str, Any] = RadixNode() root.insert_many(_SCREAMING_SNAKE_CASE ) assert all(root.find(_SCREAMING_SNAKE_CASE ) for word in words ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def lowerCAmelCase_ ( ): assert test_trie() def lowerCAmelCase_ ( ): UpperCamelCase_ : List[str] = RadixNode() UpperCamelCase_ : Optional[int] = """banana bananas bandanas bandana band apple all beast""".split() root.insert_many(_SCREAMING_SNAKE_CASE ) print("""Words:""" , _SCREAMING_SNAKE_CASE ) print("""Tree:""" ) root.print_tree() if __name__ == "__main__": main()
138
import numpy as np def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : np.ndarray , _SCREAMING_SNAKE_CASE : np.ndarray , _SCREAMING_SNAKE_CASE : float = 1E-12 , _SCREAMING_SNAKE_CASE : int = 100 , ): assert np.shape(_SCREAMING_SNAKE_CASE )[0] == np.shape(_SCREAMING_SNAKE_CASE )[1] # Ensure proper dimensionality. assert np.shape(_SCREAMING_SNAKE_CASE )[0] == np.shape(_SCREAMING_SNAKE_CASE )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(_SCREAMING_SNAKE_CASE ) == np.iscomplexobj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : Optional[Any] = np.iscomplexobj(_SCREAMING_SNAKE_CASE ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(_SCREAMING_SNAKE_CASE , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. UpperCamelCase_ : Optional[int] = False UpperCamelCase_ : str = 0 UpperCamelCase_ : Optional[int] = 0 UpperCamelCase_ : List[str] = 1E12 while not convergence: # Multiple matrix by the vector. UpperCamelCase_ : Optional[Any] = np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Normalize the resulting output vector. UpperCamelCase_ : Union[str, Any] = w / np.linalg.norm(_SCREAMING_SNAKE_CASE ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) UpperCamelCase_ : Tuple = vector.conj().T if is_complex else vector.T UpperCamelCase_ : Tuple = np.dot(_SCREAMING_SNAKE_CASE , np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # Check convergence. UpperCamelCase_ : Union[str, Any] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: UpperCamelCase_ : List[Any] = True UpperCamelCase_ : Dict = lambda_ if is_complex: UpperCamelCase_ : List[Any] = np.real(lambda_ ) return lambda_, vector def lowerCAmelCase_ ( ): UpperCamelCase_ : Tuple = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) UpperCamelCase_ : List[Any] = np.array([41, 4, 20] ) UpperCamelCase_ : str = real_input_matrix.astype(np.complexaaa ) UpperCamelCase_ : str = np.triu(1j * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T UpperCamelCase_ : List[Any] = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": UpperCamelCase_ : Tuple = real_input_matrix UpperCamelCase_ : Any = real_vector elif problem_type == "complex": UpperCamelCase_ : List[Any] = complex_input_matrix UpperCamelCase_ : List[str] = complex_vector # Our implementation. UpperCamelCase_,UpperCamelCase_ : List[Any] = power_iteration(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). UpperCamelCase_,UpperCamelCase_ : int = np.linalg.eigh(_SCREAMING_SNAKE_CASE ) # Last eigenvalue is the maximum one. UpperCamelCase_ : Union[str, Any] = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. UpperCamelCase_ : int = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(_SCREAMING_SNAKE_CASE ) - np.abs(_SCREAMING_SNAKE_CASE ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
138
1
from __future__ import annotations def A ( __UpperCamelCase = 4 ) -> list[list[int]]: A__ = abs(__UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(__UpperCamelCase )] for y in range(__UpperCamelCase )] def A ( __UpperCamelCase ) -> list[list[int]]: return reverse_row(transpose(__UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def A ( __UpperCamelCase ) -> list[list[int]]: return reverse_row(reverse_column(__UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def A ( __UpperCamelCase ) -> list[list[int]]: return reverse_column(transpose(__UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def A ( __UpperCamelCase ) -> list[list[int]]: A__ = [list(__UpperCamelCase ) for x in zip(*__UpperCamelCase )] return matrix def A ( __UpperCamelCase ) -> list[list[int]]: A__ = matrix[::-1] return matrix def A ( __UpperCamelCase ) -> list[list[int]]: A__ = [x[::-1] for x in matrix] return matrix def A ( __UpperCamelCase ) -> None: for i in matrix: print(*__UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) SCREAMING_SNAKE_CASE__ = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) SCREAMING_SNAKE_CASE__ = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
9
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __magic_name__ ( __UpperCAmelCase): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = "Speech2TextFeatureExtractor" SCREAMING_SNAKE_CASE__ : List[str] = "Speech2TextTokenizer" def __init__( self: List[str] , _lowerCamelCase: str , _lowerCamelCase: Optional[Any] ): super().__init__(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False def __call__( self: List[str] , *_lowerCamelCase: Dict , **_lowerCamelCase: List[str] ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_lowerCamelCase , **_lowerCamelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''raw_speech''' ) else: SCREAMING_SNAKE_CASE_ = kwargs.pop('''audio''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''sampling_rate''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''text''' , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: SCREAMING_SNAKE_CASE_ = args[0] SCREAMING_SNAKE_CASE_ = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: SCREAMING_SNAKE_CASE_ = self.feature_extractor(_lowerCamelCase , *_lowerCamelCase , sampling_rate=_lowerCamelCase , **_lowerCamelCase ) if text is not None: SCREAMING_SNAKE_CASE_ = self.tokenizer(_lowerCamelCase , **_lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE_ = encodings['''input_ids'''] return inputs def _A ( self: List[str] , *_lowerCamelCase: List[Any] , **_lowerCamelCase: Union[str, Any] ): return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def _A ( self: Union[str, Any] , *_lowerCamelCase: str , **_lowerCamelCase: Optional[Any] ): return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @contextmanager def _A ( self: List[Any] ): warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = self.tokenizer yield SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False
234
0
import math def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): 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(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 10_001 ): try: __lowerCamelCase : Any = int(__lowerCAmelCase ) except (TypeError, ValueError): raise TypeError('Parameter nth must be int or castable to int.' ) from None if nth <= 0: raise ValueError('Parameter nth must be greater than or equal to one.' ) __lowerCamelCase : Any = [] __lowerCamelCase : Optional[Any] = 2 while len(__lowerCAmelCase ) < nth: if is_prime(__lowerCAmelCase ): primes.append(__lowerCAmelCase ) num += 1 else: num += 1 return primes[len(__lowerCAmelCase ) - 1] if __name__ == "__main__": print(F"""{solution() = }""")
709
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
230
0
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class __magic_name__ ( __SCREAMING_SNAKE_CASE ): def __init__( self , snake_case_ , snake_case_ ): super().__init__() self.register_modules(unet=snake_case_ , scheduler=snake_case_ ) @torch.no_grad() def __call__( self , snake_case_ = 1 , snake_case_ = None , snake_case_ = 50 , snake_case_ = "pil" , snake_case_ = True , **snake_case_ , ): lowercase =torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=snake_case_ , ) lowercase =image.to(self.device ) # set step values self.scheduler.set_timesteps(snake_case_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowercase =self.unet(snake_case_ , snake_case_ ).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 lowercase =self.scheduler.step(snake_case_ , snake_case_ , snake_case_ ).prev_sample lowercase =(image / 2 + 0.5).clamp(0 , 1 ) lowercase =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowercase =self.numpy_to_pil(snake_case_ ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=snake_case_ ), "This is a local test"
72
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json', 'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json', } class __UpperCAmelCase ( __A ): """simple docstring""" _lowerCamelCase = """luke""" def __init__( self , __A=50267 , __A=500000 , __A=768 , __A=256 , __A=12 , __A=12 , __A=3072 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=2 , __A=0.02 , __A=1E-12 , __A=True , __A=None , __A=1 , __A=0 , __A=2 , **__A , ): super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) __a = vocab_size __a = entity_vocab_size __a = hidden_size __a = entity_emb_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = use_entity_aware_attention __a = classifier_dropout
99
0
from __future__ import annotations import math def _A ( __snake_case :int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _A ( __snake_case :int ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = str(__snake_case ) __SCREAMING_SNAKE_CASE = [n] for i in range(1 , len(__snake_case ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _A ( __snake_case :int ) -> bool: """simple docstring""" if len(str(__snake_case ) ) > 3: if not is_prime(int(str(__snake_case )[-3:] ) ) or not is_prime(int(str(__snake_case )[:3] ) ): return False return True def _A ( __snake_case :int = 11 ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 13 while len(__snake_case ) != count: if validate(__snake_case ): __SCREAMING_SNAKE_CASE = list_truncated_nums(__snake_case ) if all(is_prime(__snake_case ) for i in list_nums ): list_truncated_primes.append(__snake_case ) num += 2 return list_truncated_primes def _A ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(F"""{sum(compute_truncated_primes(11)) = }""")
214
_snake_case : str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def _A ( ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = input("Enter message: " ) __SCREAMING_SNAKE_CASE = input("Enter key [alphanumeric]: " ) __SCREAMING_SNAKE_CASE = input("Encrypt/Decrypt [e/d]: " ) if mode.lower().startswith("e" ): __SCREAMING_SNAKE_CASE = "encrypt" __SCREAMING_SNAKE_CASE = encrypt_message(__snake_case , __snake_case ) elif mode.lower().startswith("d" ): __SCREAMING_SNAKE_CASE = "decrypt" __SCREAMING_SNAKE_CASE = decrypt_message(__snake_case , __snake_case ) print(f'''\n{mode.title()}ed message:''' ) print(__snake_case ) def _A ( __snake_case :str , __snake_case :str ) -> str: """simple docstring""" return translate_message(__snake_case , __snake_case , "encrypt" ) def _A ( __snake_case :str , __snake_case :str ) -> str: """simple docstring""" return translate_message(__snake_case , __snake_case , "decrypt" ) def _A ( __snake_case :str , __snake_case :str , __snake_case :str ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = key.upper() for symbol in message: __SCREAMING_SNAKE_CASE = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__snake_case ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__snake_case ): __SCREAMING_SNAKE_CASE = 0 else: translated.append(__snake_case ) return "".join(__snake_case ) if __name__ == "__main__": main()
214
1
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed _lowerCamelCase ={ """distilbert""": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), """roberta""": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), """bert""": (BertConfig, BertForMaskedLM, BertTokenizer), """gpt2""": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def _a ( lowerCamelCase ): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def _a ( lowerCamelCase, lowerCamelCase ): if args.student_type == "roberta": lowerCamelCase : Union[str, Any] = False elif args.student_type == "gpt2": lowerCamelCase : Optional[int] = False def _a ( lowerCamelCase, lowerCamelCase ): if args.student_type == "roberta": lowerCamelCase : str = False def _a ( ): lowerCamelCase : Optional[int] = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""", action="""store_true""", help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""", type=lowerCamelCase, required=lowerCamelCase, help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""", type=lowerCamelCase, required=lowerCamelCase, help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""", ) parser.add_argument( """--student_type""", type=lowerCamelCase, choices=["""distilbert""", """roberta""", """gpt2"""], required=lowerCamelCase, help="""The student type (DistilBERT, RoBERTa).""", ) parser.add_argument("""--student_config""", type=lowerCamelCase, required=lowerCamelCase, help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""", default=lowerCamelCase, type=lowerCamelCase, help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""", choices=["""bert""", """roberta""", """gpt2"""], required=lowerCamelCase, help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""", type=lowerCamelCase, required=lowerCamelCase, help="""The teacher model.""" ) parser.add_argument("""--temperature""", default=2.0, type=lowerCamelCase, help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""", default=0.5, type=lowerCamelCase, help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""", default=0.0, type=lowerCamelCase, help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""", ) parser.add_argument("""--alpha_clm""", default=0.5, type=lowerCamelCase, help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""", default=0.0, type=lowerCamelCase, help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""", default=0.0, type=lowerCamelCase, help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""", action="""store_true""", help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""", default=0.1_5, type=lowerCamelCase, help="""Proportion of tokens for which we need to make a prediction.""", ) parser.add_argument("""--word_mask""", default=0.8, type=lowerCamelCase, help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""", default=0.1, type=lowerCamelCase, help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""", default=0.1, type=lowerCamelCase, help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""", default=0.7, type=lowerCamelCase, help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""", ) parser.add_argument("""--token_counts""", type=lowerCamelCase, help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""", action="""store_true""", help="""If true, compute the distillation loss only the [MLM] prediction distribution.""", ) parser.add_argument( """--freeze_pos_embs""", action="""store_true""", help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""", ) parser.add_argument( """--freeze_token_type_embds""", action="""store_true""", help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""", ) parser.add_argument("""--n_epoch""", type=lowerCamelCase, default=3, help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""", type=lowerCamelCase, default=5, help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""", action="""store_false""", help="""If true, group sequences that have similar length into the same batch. Default is true.""", ) parser.add_argument( """--gradient_accumulation_steps""", type=lowerCamelCase, default=50, help="""Gradient accumulation for larger training batches.""", ) parser.add_argument("""--warmup_prop""", default=0.0_5, type=lowerCamelCase, help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""", default=0.0, type=lowerCamelCase, help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""", default=5e-4, type=lowerCamelCase, help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""", default=1e-6, type=lowerCamelCase, help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""", default=5.0, type=lowerCamelCase, help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""", default=0.0_2, type=lowerCamelCase, help="""Random initialization range.""" ) parser.add_argument( """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""", ) parser.add_argument( """--fp16_opt_level""", type=lowerCamelCase, default="""O1""", help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ), ) parser.add_argument("""--n_gpu""", type=lowerCamelCase, default=1, help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""", type=lowerCamelCase, default=-1, help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""", type=lowerCamelCase, default=56, help="""Random seed""" ) parser.add_argument("""--log_interval""", type=lowerCamelCase, default=500, help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""", type=lowerCamelCase, default=4000, help="""Checkpoint interval.""" ) lowerCamelCase : str = parser.parse_args() sanity_checks(lowerCamelCase ) # ARGS # init_gpu_params(lowerCamelCase ) set_seed(lowerCamelCase ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( F'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(F'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(F'''Param: {args}''' ) with open(os.path.join(args.dump_path, """parameters.json""" ), """w""" ) as f: json.dump(vars(lowerCamelCase ), lowerCamelCase, indent=4 ) git_log(args.dump_path ) lowerCamelCase , lowerCamelCase , lowerCamelCase : Any = MODEL_CLASSES[args.student_type] lowerCamelCase , lowerCamelCase , lowerCamelCase : Dict = MODEL_CLASSES[args.teacher_type] # TOKENIZER # lowerCamelCase : List[str] = teacher_tokenizer_class.from_pretrained(args.teacher_name ) lowerCamelCase : Tuple = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): lowerCamelCase : List[Any] = tokenizer.all_special_tokens.index(lowerCamelCase ) lowerCamelCase : str = tokenizer.all_special_ids[idx] logger.info(F'''Special tokens {special_tok_ids}''' ) lowerCamelCase : List[str] = special_tok_ids lowerCamelCase : List[Any] = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F'''Loading data from {args.data_file}''' ) with open(args.data_file, """rb""" ) as fp: lowerCamelCase : Union[str, Any] = pickle.load(lowerCamelCase ) if args.mlm: logger.info(F'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts, """rb""" ) as fp: lowerCamelCase : str = pickle.load(lowerCamelCase ) lowerCamelCase : Any = np.maximum(lowerCamelCase, 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): lowerCamelCase : str = 0.0 # do not predict special tokens lowerCamelCase : int = torch.from_numpy(lowerCamelCase ) else: lowerCamelCase : int = None lowerCamelCase : Union[str, Any] = LmSeqsDataset(params=lowerCamelCase, data=lowerCamelCase ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(F'''Loading student config from {args.student_config}''' ) lowerCamelCase : Optional[Any] = student_config_class.from_pretrained(args.student_config ) lowerCamelCase : Optional[Any] = True if args.student_pretrained_weights is not None: logger.info(F'''Loading pretrained weights from {args.student_pretrained_weights}''' ) lowerCamelCase : int = student_model_class.from_pretrained(args.student_pretrained_weights, config=lowerCamelCase ) else: lowerCamelCase : List[str] = student_model_class(lowerCamelCase ) if args.n_gpu > 0: student.to(F'''cuda:{args.local_rank}''' ) logger.info("""Student loaded.""" ) # TEACHER # lowerCamelCase : Optional[Any] = teacher_model_class.from_pretrained(args.teacher_name, output_hidden_states=lowerCamelCase ) if args.n_gpu > 0: teacher.to(F'''cuda:{args.local_rank}''' ) logger.info(F'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(lowerCamelCase, lowerCamelCase ) if args.freeze_token_type_embds: freeze_token_type_embeddings(lowerCamelCase, lowerCamelCase ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() lowerCamelCase : List[Any] = Distiller( params=lowerCamelCase, dataset=lowerCamelCase, token_probs=lowerCamelCase, student=lowerCamelCase, teacher=lowerCamelCase ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
681
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : def __init__( self , __magic_name__ , __magic_name__=3 , __magic_name__=3_2 , __magic_name__=3 , __magic_name__=1_0 , __magic_name__=[1_0, 2_0, 3_0, 4_0] , __magic_name__=[1, 1, 2, 1] , __magic_name__=True , __magic_name__=True , __magic_name__="relu" , __magic_name__=3 , __magic_name__=None , ): lowerCamelCase : Tuple = parent lowerCamelCase : Tuple = batch_size lowerCamelCase : List[Any] = image_size lowerCamelCase : Optional[Any] = num_channels lowerCamelCase : Dict = embeddings_size lowerCamelCase : Optional[int] = hidden_sizes lowerCamelCase : Union[str, Any] = depths lowerCamelCase : Optional[Any] = is_training lowerCamelCase : Union[str, Any] = use_labels lowerCamelCase : Dict = hidden_act lowerCamelCase : Any = num_labels lowerCamelCase : int = scope lowerCamelCase : Optional[Any] = len(__magic_name__ ) def UpperCamelCase__ ( self ): lowerCamelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase : Tuple = None if self.use_labels: lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase : Tuple = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self ): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ , __magic_name__ ): lowerCamelCase : Dict = TFResNetModel(config=__magic_name__ ) lowerCamelCase : Tuple = model(__magic_name__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ , __magic_name__ ): lowerCamelCase : str = self.num_labels lowerCamelCase : Dict = TFResNetForImageClassification(__magic_name__ ) lowerCamelCase : Union[str, Any] = model(__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self ): lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase , lowerCamelCase : Union[str, Any] = config_and_inputs lowerCamelCase : List[str] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class A__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase): _UpperCAmelCase : Any = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _UpperCAmelCase : List[str] = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Dict = False _UpperCAmelCase : List[Any] = False _UpperCAmelCase : Any = False def UpperCamelCase__ ( self ): lowerCamelCase : int = TFResNetModelTester(self ) lowerCamelCase : str = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ ) def UpperCamelCase__ ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase__ ( self ): return @unittest.skip(reason="""ResNet does not use inputs_embeds""" ) def UpperCamelCase__ ( self ): pass @unittest.skip(reason="""ResNet does not support input and output embeddings""" ) def UpperCamelCase__ ( self ): pass def UpperCamelCase__ ( self ): lowerCamelCase , lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase : List[str] = model_class(__magic_name__ ) lowerCamelCase : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase : Tuple = [*signature.parameters.keys()] lowerCamelCase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __magic_name__ ) def UpperCamelCase__ ( self ): lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCamelCase__ ( self ): def check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ): lowerCamelCase : Any = model_class(__magic_name__ ) lowerCamelCase : List[Any] = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) lowerCamelCase : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(__magic_name__ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase , lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase : Tuple = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCamelCase : Union[str, Any] = layer_type lowerCamelCase : str = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase : int = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) def UpperCamelCase__ ( self ): lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def UpperCamelCase__ ( self ): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase : Any = TFResNetModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def _a ( ): lowerCamelCase : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class A__ ( unittest.TestCase): @cached_property def UpperCamelCase__ ( self ): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self ): lowerCamelCase : Tuple = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCamelCase : List[str] = self.default_image_processor lowerCamelCase : str = prepare_img() lowerCamelCase : Tuple = image_processor(images=__magic_name__ , return_tensors="""tf""" ) # forward pass lowerCamelCase : Tuple = model(**__magic_name__ ) # verify the logits lowerCamelCase : Optional[Any] = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) lowerCamelCase : Optional[Any] = tf.constant([-11.1_069, -9.7_877, -8.3_777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __magic_name__ , atol=1e-4 ) )
681
1
def a__ ( _UpperCamelCase : int ): __lowerCamelCase = [1] __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = 0, 0, 0 __lowerCamelCase = ugly_nums[ia] * 2 __lowerCamelCase = ugly_nums[ia] * 3 __lowerCamelCase = ugly_nums[ia] * 5 for _ in range(1 ,_UpperCamelCase ): __lowerCamelCase = min(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) ugly_nums.append(_UpperCamelCase ) if next_num == next_a: ia += 1 __lowerCamelCase = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 __lowerCamelCase = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 __lowerCamelCase = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"{ugly_numbers(200) = }")
622
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def a__ ( _UpperCamelCase : Optional[int] ,_UpperCamelCase : List[str] ,_UpperCamelCase : List[Any]=None ,_UpperCamelCase : Any=None ): if attention_mask is None: __lowerCamelCase = tf.cast(tf.math.not_equal(_UpperCamelCase ,config.pad_token_id ) ,tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class __lowerCAmelCase : lowerCAmelCase__ = OPTConfig lowerCAmelCase__ = {} lowerCAmelCase__ = """gelu""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=99 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=4 , __UpperCAmelCase=4 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=20 , __UpperCAmelCase=2 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=16 , __UpperCAmelCase=16 , ): '''simple docstring''' __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = eos_token_id __lowerCamelCase = pad_token_id __lowerCamelCase = bos_token_id __lowerCamelCase = embed_dim __lowerCamelCase = word_embed_proj_dim __lowerCamelCase = False def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __lowerCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __lowerCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __lowerCamelCase = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__UpperCAmelCase , **self.config_updates , ) __lowerCamelCase = prepare_opt_inputs_dict(__UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = TFOPTModel(config=__UpperCAmelCase ) __lowerCamelCase = inputs_dict['''input_ids'''] __lowerCamelCase = input_ids[:1, :] __lowerCamelCase = inputs_dict['''attention_mask'''][:1, :] __lowerCamelCase = 1 # first forward pass __lowerCamelCase = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase ) __lowerCamelCase ,__lowerCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowerCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __lowerCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __lowerCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __lowerCamelCase = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] __lowerCamelCase = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __lowerCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __lowerCamelCase = output_from_no_past[:, -3:, random_slice_idx] __lowerCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) @require_tf class __lowerCAmelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): lowerCAmelCase__ = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () lowerCAmelCase__ = (TFOPTForCausalLM,) if is_tf_available() else () lowerCAmelCase__ = ( {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = 1_0 def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = TFOPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=__UpperCAmelCase ) def lowerCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase ,__lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(__UpperCAmelCase , __UpperCAmelCase ): if hasattr(__UpperCAmelCase , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(__UpperCAmelCase , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings __lowerCamelCase = model_class(config=__UpperCAmelCase ) __lowerCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) __lowerCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(__UpperCAmelCase ) __lowerCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_input_embeddings() ) __lowerCamelCase = _get_word_embedding_weight(__UpperCAmelCase , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. __lowerCamelCase = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , __UpperCAmelCase ) # check that weights remain the same after resizing __lowerCamelCase = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __lowerCamelCase = False self.assertTrue(__UpperCAmelCase ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , __UpperCAmelCase ) __lowerCamelCase = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __lowerCamelCase = False self.assertTrue(__UpperCAmelCase ) def a__ ( _UpperCamelCase : Optional[Any] ): return tf.constant(_UpperCamelCase ,dtype=tf.intaa ) @require_tf class __lowerCAmelCase ( unittest.TestCase ): lowerCAmelCase__ = 9_9 def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = tf.ones((4, 1) , dtype=tf.intaa ) * 2 __lowerCamelCase = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) __lowerCamelCase = input_ids.shape[0] __lowerCamelCase = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) __lowerCamelCase = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) __lowerCamelCase = tf.not_equal(__UpperCAmelCase , model.config.pad_token_id ) with tf.GradientTape(): __lowerCamelCase = model(input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase ).last_hidden_state __lowerCamelCase = (1, 11, 512) self.assertEqual(output.shape , __UpperCAmelCase ) __lowerCamelCase = tf.constant( [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-3 ) ) __lowerCamelCase = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) __lowerCamelCase = xla_generate(__UpperCAmelCase , __UpperCAmelCase )[0] self.assertTrue(np.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=4E-2 ) ) @require_tf @slow class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): '''simple docstring''' super().setUp() __lowerCamelCase = '''facebook/opt-350m''' def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = TFOPTForCausalLM.from_pretrained(self.path_model ) __lowerCamelCase = GPTaTokenizer.from_pretrained(self.path_model ) __lowerCamelCase = [ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False __lowerCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' , padding=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) __lowerCamelCase = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) __lowerCamelCase = tf.constant( [ [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670], [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822], [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703], [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477], ] ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) __lowerCamelCase = tf.function(__UpperCAmelCase , jit_compile=__UpperCAmelCase ) __lowerCamelCase = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) ) @require_tf @slow class __lowerCAmelCase ( unittest.TestCase ): @property def lowerCamelCase ( self ): '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = '''facebook/opt-125m''' __lowerCamelCase = [ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] __lowerCamelCase = [] __lowerCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __lowerCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: __lowerCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' ).input_ids __lowerCamelCase = model.generate(__UpperCAmelCase , max_length=10 ) __lowerCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = '''facebook/opt-350m''' __lowerCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __lowerCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) __lowerCamelCase = '''left''' # use different length sentences to test batching __lowerCamelCase = [ '''Hello, my dog is a little''', '''Today, I''', ] __lowerCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' , padding=__UpperCAmelCase ) __lowerCamelCase = inputs['''input_ids'''] __lowerCamelCase = model.generate(input_ids=__UpperCAmelCase , attention_mask=inputs['''attention_mask'''] ) __lowerCamelCase = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids __lowerCamelCase = model.generate(input_ids=__UpperCAmelCase ) __lowerCamelCase = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) __lowerCamelCase = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids __lowerCamelCase = model.generate(input_ids=__UpperCAmelCase , max_length=model.config.max_length - num_paddings ) __lowerCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) __lowerCamelCase = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__UpperCAmelCase ) __lowerCamelCase = tokenizer.decode(output_padded[0] , skip_special_tokens=__UpperCAmelCase ) __lowerCamelCase = [ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , [non_padded_sentence, padded_sentence] ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = '''facebook/opt-350m''' __lowerCamelCase = [ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] __lowerCamelCase = [] __lowerCamelCase = GPTaTokenizer.from_pretrained(__UpperCAmelCase ) __lowerCamelCase = TFOPTForCausalLM.from_pretrained(__UpperCAmelCase ) for prompt in self.prompts: __lowerCamelCase = tokenizer(__UpperCAmelCase , return_tensors='''tf''' ).input_ids __lowerCamelCase = model.generate(__UpperCAmelCase , max_length=10 ) __lowerCamelCase = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
622
1
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 snake_case ( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] UpperCAmelCase : Optional[List[bool]] 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 snake_case ( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase : np.ndarray UpperCAmelCase : List[bool] 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
393
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available 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 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 A_ = get_tests_dir("fixtures/dummy_feature_extractor_config.json") A_ = get_tests_dir("fixtures/vocab.json") A_ = get_tests_dir("fixtures") class snake_case ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : str = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] def _lowercase ( self : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ = 0 def _lowercase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''' ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ = WavaVecaConfig() SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''' ) # save in new folder model_config.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) ) copyfile(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , '''vocab.json''' ) ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''' ) SCREAMING_SNAKE_CASE_ = WavaVecaProcessor(lowerCAmelCase_ , lowerCAmelCase_ ) # save in new folder processor.save_pretrained(lowerCAmelCase_ ) # drop `processor_class` in tokenizer with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , '''r''' ) as f: SCREAMING_SNAKE_CASE_ = json.load(lowerCAmelCase_ ) config_dict.pop('''processor_class''' ) with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , '''w''' ) as f: f.write(json.dumps(lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : Any ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''' ) SCREAMING_SNAKE_CASE_ = WavaVecaProcessor(lowerCAmelCase_ , lowerCAmelCase_ ) # save in new folder processor.save_pretrained(lowerCAmelCase_ ) # drop `processor_class` in feature extractor with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , '''r''' ) as f: SCREAMING_SNAKE_CASE_ = json.load(lowerCAmelCase_ ) config_dict.pop('''processor_class''' ) with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , '''w''' ) as f: f.write(json.dumps(lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : Union[str, Any] ) -> Dict: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ = WavaVecaConfig(processor_class='''Wav2Vec2Processor''' ) model_config.save_pretrained(lowerCAmelCase_ ) # copy relevant files copyfile(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , '''vocab.json''' ) ) # create emtpy sample processor with open(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , '''w''' ) as f: f.write('''{}''' ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" with self.assertRaises(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowerCAmelCase_ ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''' ) SCREAMING_SNAKE_CASE_ = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) SCREAMING_SNAKE_CASE_ = processor.tokenizer 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_ = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowerCAmelCase_ , use_fast=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def _lowercase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" try: AutoConfig.register('''custom''' , lowerCAmelCase_ ) AutoFeatureExtractor.register(lowerCAmelCase_ , lowerCAmelCase_ ) AutoTokenizer.register(lowerCAmelCase_ , slow_tokenizer_class=lowerCAmelCase_ ) AutoProcessor.register(lowerCAmelCase_ , lowerCAmelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCAmelCase_ ): AutoProcessor.register(lowerCAmelCase_ , lowerCAmelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE_ = CustomFeatureExtractor.from_pretrained(lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = os.path.join(lowerCAmelCase_ , '''vocab.txt''' ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE_ = CustomTokenizer(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = CustomProcessor(lowerCAmelCase_ , lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) 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] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase ( self : Dict ) -> int: """simple docstring""" class snake_case ( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase : Dict = False class snake_case ( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase : List[Any] = False class snake_case ( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase : List[Any] = """AutoFeatureExtractor""" UpperCAmelCase : Tuple = """AutoTokenizer""" UpperCAmelCase : List[Any] = False try: AutoConfig.register('''custom''' , lowerCAmelCase_ ) AutoFeatureExtractor.register(lowerCAmelCase_ , lowerCAmelCase_ ) AutoTokenizer.register(lowerCAmelCase_ , slow_tokenizer_class=lowerCAmelCase_ ) AutoProcessor.register(lowerCAmelCase_ , lowerCAmelCase_ ) # If remote code is not set, the default is to use local classes. SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''' ) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowerCAmelCase_ ) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowerCAmelCase_ ) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''' ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) 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] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(processor.__class__.__name__ , '''BertTokenizerFast''' ) def _lowercase ( self : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext''' ) self.assertEqual(processor.__class__.__name__ , '''ConvNextImageProcessor''' ) @is_staging_test class snake_case ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Any = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def _lowercase ( cls : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ = TOKEN HfFolder.save_token(lowerCAmelCase_ ) @classmethod def _lowercase ( cls : Dict ) -> List[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-processor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-processor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-processor''' ) except HTTPError: pass def _lowercase ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ = WavaVecaProcessor.from_pretrained(lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowerCAmelCase_ , '''test-processor''' ) , push_to_hub=lowerCAmelCase_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = WavaVecaProcessor.from_pretrained(F'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowerCAmelCase_ , getattr(new_processor.feature_extractor , lowerCAmelCase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ = WavaVecaProcessor.from_pretrained(lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowerCAmelCase_ , '''test-processor-org''' ) , push_to_hub=lowerCAmelCase_ , use_auth_token=self._token , organization='''valid_org''' , ) SCREAMING_SNAKE_CASE_ = WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowerCAmelCase_ , getattr(new_processor.feature_extractor , lowerCAmelCase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def _lowercase ( self : Any ) -> Union[str, Any]: """simple docstring""" CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE_ = CustomFeatureExtractor.from_pretrained(lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = os.path.join(lowerCAmelCase_ , '''vocab.txt''' ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE_ = CustomTokenizer(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = CustomProcessor(lowerCAmelCase_ , lowerCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'''{USER}/test-dynamic-processor''' , token=self._token ) SCREAMING_SNAKE_CASE_ = Repository(lowerCAmelCase_ , clone_from=F'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(lowerCAmelCase_ ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''', '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(lowerCAmelCase_ , '''tokenizer_config.json''' ) ) as f: SCREAMING_SNAKE_CASE_ = json.load(lowerCAmelCase_ ) self.assertDictEqual( tokenizer_config['''auto_map'''] , { '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None], '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(lowerCAmelCase_ , '''custom_feature_extraction.py''' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowerCAmelCase_ , '''custom_tokenization.py''' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowerCAmelCase_ , '''custom_processing.py''' ) ) ) repo.push_to_hub() SCREAMING_SNAKE_CASE_ = AutoProcessor.from_pretrained(F'''{USER}/test-dynamic-processor''' , trust_remote_code=lowerCAmelCase_ ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , '''CustomProcessor''' )
393
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) class a__( snake_case__ ): a_ : List[Any] = '''encoder-decoder''' a_ : Dict = True def __init__( self , **_UpperCAmelCase ) -> Optional[int]: super().__init__(**_UpperCAmelCase ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case__ =kwargs.pop('encoder' ) snake_case__ =encoder_config.pop('model_type' ) snake_case__ =kwargs.pop('decoder' ) snake_case__ =decoder_config.pop('model_type' ) from ..auto.configuration_auto import AutoConfig snake_case__ =AutoConfig.for_model(_UpperCAmelCase , **_UpperCAmelCase ) snake_case__ =AutoConfig.for_model(_UpperCAmelCase , **_UpperCAmelCase ) snake_case__ =True @classmethod def _lowercase ( cls , _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase ) -> PretrainedConfig: logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' ) snake_case__ =True snake_case__ =True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_UpperCAmelCase ) def _lowercase ( self ) -> int: snake_case__ =copy.deepcopy(self.__dict__ ) snake_case__ =self.encoder.to_dict() snake_case__ =self.decoder.to_dict() snake_case__ =self.__class__.model_type return output
714
'''simple docstring''' from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def a ( ) -> str: snake_case__ , snake_case__ =9, 14 # noqa: F841 snake_case__ =[ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] snake_case__ =defaultdict(UpperCamelCase_ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) snake_case__ =mst(UpperCamelCase_ ) snake_case__ =[ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: snake_case__ =tuple(answer[:2] ) snake_case__ =tuple(edge[::-1] ) assert edge in result or reverse in result
581
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=1_8 , lowercase=3_0 , lowercase=4_0_0 , lowercase=True , lowercase=None , lowercase=True , lowercase=None , lowercase=True , lowercase=[0.5, 0.5, 0.5] , lowercase=[0.5, 0.5, 0.5] , ) -> str: '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''shortest_edge''': 1_8} __SCREAMING_SNAKE_CASE : List[Any] = crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Optional[Any] = batch_size __SCREAMING_SNAKE_CASE : Tuple = num_channels __SCREAMING_SNAKE_CASE : Dict = image_size __SCREAMING_SNAKE_CASE : Optional[Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Optional[Any] = do_resize __SCREAMING_SNAKE_CASE : List[Any] = size __SCREAMING_SNAKE_CASE : Dict = do_center_crop __SCREAMING_SNAKE_CASE : Tuple = crop_size __SCREAMING_SNAKE_CASE : Dict = do_normalize __SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean __SCREAMING_SNAKE_CASE : List[Any] = image_std def _snake_case ( self ) -> List[Any]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( snake_case , unittest.TestCase ): __a : Dict = LevitImageProcessor if is_vision_available() else None def _snake_case ( self ) -> Dict: '''simple docstring''' __SCREAMING_SNAKE_CASE : int = LevitImageProcessingTester(self ) @property def _snake_case ( self ) -> Any: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self ) -> int: '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase , '''image_mean''' ) ) self.assertTrue(hasattr(lowercase , '''image_std''' ) ) self.assertTrue(hasattr(lowercase , '''do_normalize''' ) ) self.assertTrue(hasattr(lowercase , '''do_resize''' ) ) self.assertTrue(hasattr(lowercase , '''do_center_crop''' ) ) self.assertTrue(hasattr(lowercase , '''size''' ) ) def _snake_case ( self ) -> Tuple: '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8} ) self.assertEqual(image_processor.crop_size , {'''height''': 1_8, '''width''': 1_8} ) __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2} ) self.assertEqual(image_processor.crop_size , {'''height''': 8_4, '''width''': 8_4} ) def _snake_case ( self ) -> Union[str, Any]: '''simple docstring''' pass def _snake_case ( self ) -> Tuple: '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Tuple = image_processing(lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _snake_case ( self ) -> int: '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , numpify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : str = image_processing(lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _snake_case ( self ) -> Dict: '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , torchify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : int = image_processing(lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
158
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class SCREAMING_SNAKE_CASE_ ( datasets.BeamBasedBuilder ): def _snake_case ( self ) -> Tuple: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({'''content''': datasets.Value('''string''' )} ) , supervised_keys=lowercase , ) def _snake_case ( self , lowercase , lowercase ) -> str: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_dummy_examples()} )] def _snake_case ( self , lowercase , lowercase ) -> Any: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowercase ) class SCREAMING_SNAKE_CASE_ ( datasets.BeamBasedBuilder ): def _snake_case ( self ) -> Tuple: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) , supervised_keys=lowercase , ) def _snake_case ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_nested_examples()} ) ] def _snake_case ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowercase ) def A_ ( ) -> Optional[int]: return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] def A_ ( ) -> Dict: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] class SCREAMING_SNAKE_CASE_ ( snake_case ): @require_beam def _snake_case ( self ) -> str: '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __SCREAMING_SNAKE_CASE : Optional[int] = DummyBeamDataset(cache_dir=lowercase , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) __SCREAMING_SNAKE_CASE : List[Any] = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , lowercase ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , lowercase ) self.assertDictEqual(dset['''train'''][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def _snake_case ( self ) -> List[str]: '''simple docstring''' import apache_beam as beam __SCREAMING_SNAKE_CASE : Optional[int] = beam.io.parquetio.WriteToParquet __SCREAMING_SNAKE_CASE : Union[str, Any] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __SCREAMING_SNAKE_CASE : Optional[Any] = DummyBeamDataset(cache_dir=lowercase , beam_runner='''DirectRunner''' ) with patch('''apache_beam.io.parquetio.WriteToParquet''' ) as write_parquet_mock: __SCREAMING_SNAKE_CASE : List[Any] = partial(lowercase , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) __SCREAMING_SNAKE_CASE : Optional[int] = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , lowercase ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , lowercase ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset['''train''']['''content'''] ) , sorted(['''foo''', '''bar''', '''foobar'''] ) ) self.assertTrue( os.path.exists(os.path.join(lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def _snake_case ( self ) -> Tuple: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_cache_dir: __SCREAMING_SNAKE_CASE : str = DummyBeamDataset(cache_dir=lowercase ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def _snake_case ( self ) -> List[str]: '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __SCREAMING_SNAKE_CASE : Union[str, Any] = NestedBeamDataset(cache_dir=lowercase , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowercase , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) ) __SCREAMING_SNAKE_CASE : Tuple = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , lowercase ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , lowercase ) self.assertDictEqual(dset['''train'''][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowercase , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset
158
1
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->int: _UpperCAmelCase , _UpperCAmelCase =len(_lowerCamelCase ), len(grid[0] ) if ( min(_lowerCamelCase , _lowerCamelCase ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _UpperCAmelCase =0 count += depth_first_search(_lowerCamelCase , row + 1 , _lowerCamelCase , _lowerCamelCase ) count += depth_first_search(_lowerCamelCase , row - 1 , _lowerCamelCase , _lowerCamelCase ) count += depth_first_search(_lowerCamelCase , _lowerCamelCase , col + 1 , _lowerCamelCase ) count += depth_first_search(_lowerCamelCase , _lowerCamelCase , col - 1 , _lowerCamelCase ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
592
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ : Optional[int] = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatureExtractor'], 'processing_mctct': ['MCTCTProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Optional[int] = [ 'MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MCTCTForCTC', 'MCTCTModel', 'MCTCTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys snake_case__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
592
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer lowercase__ : Union[str, Any] = logging.get_logger(__name__) lowercase__ : Any = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowercase__ : int = [ '''small''', '''small-base''', '''medium''', '''medium-base''', '''intermediate''', '''intermediate-base''', '''large''', '''large-base''', '''xlarge''', '''xlarge-base''', ] lowercase__ : List[str] = { '''vocab_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json''', '''funnel-transformer/small-base''': ( '''https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json''', '''funnel-transformer/large-base''': ( '''https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json''' ), }, } lowercase__ : int = {f'funnel-transformer/{name}': 5_1_2 for name in _model_names} lowercase__ : List[Any] = {f'funnel-transformer/{name}': {'''do_lower_case''': True} for name in _model_names} class lowercase_ ( UpperCamelCase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = VOCAB_FILES_NAMES UpperCAmelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ : str = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase_ : Any = FunnelTokenizer UpperCAmelCase_ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ : int = 2 def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<sep>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<cls>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="##" , **__SCREAMING_SNAKE_CASE , ) ->Any: super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , clean_text=__SCREAMING_SNAKE_CASE , tokenize_chinese_chars=__SCREAMING_SNAKE_CASE , strip_accents=__SCREAMING_SNAKE_CASE , wordpieces_prefix=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get('''strip_accents''' , __SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): lowerCAmelCase = getattr(__SCREAMING_SNAKE_CASE , normalizer_state.pop('''type''' ) ) lowerCAmelCase = do_lower_case lowerCAmelCase = strip_accents lowerCAmelCase = tokenize_chinese_chars lowerCAmelCase = normalizer_class(**__SCREAMING_SNAKE_CASE ) lowerCAmelCase = do_lower_case def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ) ->Union[str, Any]: lowerCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) ->List[int]: lowerCAmelCase = [self.sep_token_id] lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) ->Tuple[str]: lowerCAmelCase = self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE ) return tuple(__SCREAMING_SNAKE_CASE )
312
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class lowercase_ ( UpperCamelCase_ ): """simple docstring""" def __lt__( self , __SCREAMING_SNAKE_CASE ) ->Optional[int]: return self[-1] < other[-1] def __eq__( self , __SCREAMING_SNAKE_CASE ) ->Dict: return self[-1] == other[-1] def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> list: lowerCAmelCase = [] # sort into stacks for element in collection: lowerCAmelCase = Stack([element] ) lowerCAmelCase = bisect_left(snake_case__ , snake_case__ ) if i != len(snake_case__ ): stacks[i].append(snake_case__ ) else: stacks.append(snake_case__ ) # use a heap-based merge to merge stack efficiently lowerCAmelCase = merge(*(reversed(snake_case__ ) for stack in stacks) ) return collection if __name__ == "__main__": lowercase__ : int = input('''Enter numbers separated by a comma:\n''').strip() lowercase__ : str = [int(item) for item in user_input.split(''',''')] print(patience_sort(unsorted))
312
1
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar A : Any = TypeVar("""T""") def snake_case_ ( a__ : int ): """simple docstring""" return (position - 1) // 2 def snake_case_ ( a__ : int ): """simple docstring""" return (2 * position) + 1 def snake_case_ ( a__ : int ): """simple docstring""" return (2 * position) + 2 class SCREAMING_SNAKE_CASE( Generic[T] ): def __init__( self ) -> None: """simple docstring""" __lowercase = [] __lowercase = {} __lowercase = 0 def __len__( self ) -> int: """simple docstring""" return self.elements def __repr__( self ) -> str: """simple docstring""" return str(self.heap ) def snake_case__ ( self ) -> bool: """simple docstring""" return self.elements == 0 def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> None: """simple docstring""" self.heap.append((elem, weight) ) __lowercase = self.elements self.elements += 1 self._bubble_up(lowerCamelCase__ ) def snake_case__ ( self ) -> T: """simple docstring""" if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowercase ,__lowercase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowercase ,__lowercase = self.heap[0] self._bubble_down(lowerCamelCase__ ) return elem def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> None: """simple docstring""" __lowercase = self.position_map[elem] __lowercase = (elem, weight) if position > 0: __lowercase = get_parent_position(lowerCamelCase__ ) __lowercase ,__lowercase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowerCamelCase__ ) else: self._bubble_down(lowerCamelCase__ ) else: self._bubble_down(lowerCamelCase__ ) def snake_case__ ( self , lowerCamelCase__ ) -> None: """simple docstring""" __lowercase = self.position_map[elem] if curr_pos == 0: return None __lowercase = get_parent_position(lowerCamelCase__ ) __lowercase ,__lowercase = self.heap[curr_pos] __lowercase ,__lowercase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowerCamelCase__ , lowerCamelCase__ ) return self._bubble_up(lowerCamelCase__ ) return None def snake_case__ ( self , lowerCamelCase__ ) -> None: """simple docstring""" __lowercase = self.position_map[elem] __lowercase ,__lowercase = self.heap[curr_pos] __lowercase = get_child_left_position(lowerCamelCase__ ) __lowercase = get_child_right_position(lowerCamelCase__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowercase ,__lowercase = self.heap[child_left_position] __lowercase ,__lowercase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowerCamelCase__ , lowerCamelCase__ ) return self._bubble_down(lowerCamelCase__ ) if child_left_position < self.elements: __lowercase ,__lowercase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowerCamelCase__ , lowerCamelCase__ ) return self._bubble_down(lowerCamelCase__ ) else: return None if child_right_position < self.elements: __lowercase ,__lowercase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowerCamelCase__ , lowerCamelCase__ ) return self._bubble_down(lowerCamelCase__ ) return None def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> None: """simple docstring""" __lowercase = self.heap[nodea_pos][0] __lowercase = self.heap[nodea_pos][0] __lowercase ,__lowercase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowercase = nodea_pos __lowercase = nodea_pos class SCREAMING_SNAKE_CASE( Generic[T] ): def __init__( self ) -> None: """simple docstring""" __lowercase = {} __lowercase = 0 def __repr__( self ) -> str: """simple docstring""" return str(self.connections ) def __len__( self ) -> int: """simple docstring""" return self.nodes def snake_case__ ( self , lowerCamelCase__ ) -> None: """simple docstring""" if node not in self.connections: __lowercase = {} self.nodes += 1 def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> None: """simple docstring""" self.add_node(lowerCamelCase__ ) self.add_node(lowerCamelCase__ ) __lowercase = weight __lowercase = weight def snake_case_ ( a__ : GraphUndirectedWeighted[T] ,): """simple docstring""" __lowercase = {node: maxsize for node in graph.connections} __lowercase = {node: None for node in graph.connections} __lowercase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ ,a__ ) if priority_queue.is_empty(): return dist, parent # initialization __lowercase = priority_queue.extract_min() __lowercase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowercase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ ,dist[neighbour] ) __lowercase = node # running prim's algorithm while not priority_queue.is_empty(): __lowercase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowercase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ ,dist[neighbour] ) __lowercase = node return dist, parent
163
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class SCREAMING_SNAKE_CASE( datasets.BeamBasedBuilder ): def snake_case__ ( self ) -> Optional[Any]: """simple docstring""" return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=lowerCamelCase__ , ) def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> int: """simple docstring""" import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE( datasets.BeamBasedBuilder ): def snake_case__ ( self ) -> int: """simple docstring""" return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=lowerCamelCase__ , ) def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> Any: """simple docstring""" return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: """simple docstring""" import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowerCamelCase__ ) def snake_case_ ( ): """simple docstring""" return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def snake_case_ ( ): """simple docstring""" return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class SCREAMING_SNAKE_CASE( __A ): @require_beam def snake_case__ ( self ) -> Union[str, Any]: """simple docstring""" __lowercase = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __lowercase = DummyBeamDataset(cache_dir=lowerCamelCase__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , F'{builder.name}-train.arrow' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) __lowercase = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , lowerCamelCase__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , lowerCamelCase__ ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def snake_case__ ( self ) -> List[Any]: """simple docstring""" import apache_beam as beam __lowercase = beam.io.parquetio.WriteToParquet __lowercase = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __lowercase = DummyBeamDataset(cache_dir=lowerCamelCase__ , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: __lowercase = partial(lowerCamelCase__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , F'{builder.name}-train-00000-of-00002.arrow' ) ) ) self.assertTrue( os.path.exists( os.path.join( lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , F'{builder.name}-train-00000-of-00002.arrow' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) __lowercase = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , lowerCamelCase__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , lowerCamelCase__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def snake_case__ ( self ) -> Dict: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_cache_dir: __lowercase = DummyBeamDataset(cache_dir=lowerCamelCase__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def snake_case__ ( self ) -> Union[str, Any]: """simple docstring""" __lowercase = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __lowercase = NestedBeamDataset(cache_dir=lowerCamelCase__ , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , F'{builder.name}-train.arrow' ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) __lowercase = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , lowerCamelCase__ ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , lowerCamelCase__ ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowerCamelCase__ , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
163
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Optional[int] = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Union[str, Any] = [ '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 __magic_name__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
281
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __snake_case (lowerCamelCase ): __a = ['''image_processor''', '''tokenizer'''] __a = '''LayoutLMv2ImageProcessor''' __a = ('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''') def __init__( self: Any , A_: Optional[Any]=None , A_: Dict=None , **A_: Any ): if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , A_ , ) __lowerCamelCase = kwargs.pop("""feature_extractor""" ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(A_ , A_ ) def __call__( self: List[str] , A_: Any , A_: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , A_: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , A_: Union[List[List[int]], List[List[List[int]]]] = None , A_: Optional[Union[List[int], List[List[int]]]] = None , A_: bool = True , A_: Union[bool, str, PaddingStrategy] = False , A_: Union[bool, str, TruncationStrategy] = None , A_: Optional[int] = None , A_: int = 0 , A_: Optional[int] = None , A_: Optional[bool] = None , A_: Optional[bool] = None , A_: bool = False , A_: bool = False , A_: bool = False , A_: bool = False , A_: bool = True , A_: Optional[Union[str, TensorType]] = None , **A_: Any , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes """ """if you initialized the image processor with apply_ocr set to True.""" ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""" ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping.""" ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=A_ , return_tensors=A_ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(A_ , A_ ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features["""words"""] __lowerCamelCase = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=A_ , add_special_tokens=A_ , padding=A_ , truncation=A_ , max_length=A_ , stride=A_ , pad_to_multiple_of=A_ , return_token_type_ids=A_ , return_attention_mask=A_ , return_overflowing_tokens=A_ , return_special_tokens_mask=A_ , return_offsets_mapping=A_ , return_length=A_ , verbose=A_ , return_tensors=A_ , **A_ , ) # add pixel values __lowerCamelCase = features.pop("""pixel_values""" ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(A_ , encoded_inputs["""overflow_to_sample_mapping"""] ) __lowerCamelCase = images return encoded_inputs def __a ( self: Optional[Any] , A_: Any , A_: Tuple ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(A_ ) != len(A_ ): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" f' {len(A_ )} and {len(A_ )}' ) return images_with_overflow def __a ( self: Optional[Any] , *A_: str , **A_: Dict ): return self.tokenizer.batch_decode(*A_ , **A_ ) def __a ( self: Union[str, Any] , *A_: Optional[Any] , **A_: Tuple ): return self.tokenizer.decode(*A_ , **A_ ) @property def __a ( self: Union[str, Any] ): return ["input_ids", "bbox", "attention_mask", "image"] @property def __a ( self: Optional[Any] ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , A_ , ) return self.image_processor_class @property def __a ( self: List[Any] ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , A_ , ) return self.image_processor
281
1
def UpperCAmelCase_ ( __UpperCamelCase ): if not isinstance(__UpperCamelCase, __UpperCamelCase ): raise TypeError("""Input value must be an 'int' type""" ) SCREAMING_SNAKE_CASE__ =0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
588
import warnings from functools import wraps from typing import Callable def UpperCAmelCase_ ( __UpperCamelCase ): @wraps(__UpperCamelCase ) def _inner_fn(*__UpperCamelCase, **__UpperCamelCase ): warnings.warn( (f"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future."""), __UpperCamelCase, ) return fn(*__UpperCamelCase, **__UpperCamelCase ) return _inner_fn
588
1
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class a ( __lowerCAmelCase ): """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , **lowerCAmelCase_ , ) -> Tuple: super().__init__(features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _A = Sql( cache_dir=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , sql=__SCREAMING_SNAKE_CASE , con=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase ( self ) -> int: _A = None _A = None _A = None _A = None self.builder.download_and_prepare( download_config=__SCREAMING_SNAKE_CASE , download_mode=__SCREAMING_SNAKE_CASE , verification_mode=__SCREAMING_SNAKE_CASE , base_path=__SCREAMING_SNAKE_CASE , ) # Build dataset for splits _A = self.builder.as_dataset( split="""train""" , verification_mode=__SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory ) return dataset class a : """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , **lowerCAmelCase_ , ) -> Tuple: if num_proc is not None and num_proc <= 0: raise ValueError(F'''num_proc {num_proc} must be an integer > 0.''' ) _A = dataset _A = name _A = con _A = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _A = num_proc _A = to_sql_kwargs def UpperCAmelCase ( self ) -> int: _A = self.to_sql_kwargs.pop("""sql""" , __SCREAMING_SNAKE_CASE ) _A = self.to_sql_kwargs.pop("""con""" , __SCREAMING_SNAKE_CASE ) _A = self.to_sql_kwargs.pop("""index""" , __SCREAMING_SNAKE_CASE ) _A = self._write(index=__SCREAMING_SNAKE_CASE , **self.to_sql_kwargs ) return written def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Optional[int]: _A , _A , _A = args _A = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs _A = query_table( table=self.dataset.data , key=slice(__SCREAMING_SNAKE_CASE , offset + self.batch_size ) , indices=self.dataset._indices , ) _A = batch.to_pandas() _A = df.to_sql(self.name , self.con , index=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return num_rows or len(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , lowerCAmelCase_ , **lowerCAmelCase_ ) -> int: _A = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _A , _A = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
401
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = IFInpaintingPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = PipelineTesterMixin.required_optional_params - {"latents"} def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" return self._get_dummy_components() def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict=0 ) -> Any: """simple docstring""" 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 = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" self._test_save_load_local() def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
627
0
'''simple docstring''' def _UpperCAmelCase ( _UpperCamelCase : list ) -> list: for i in range(len(_UpperCamelCase ) - 1, 0, -1 ): A_ = False for j in range(_UpperCamelCase, 0, -1 ): if unsorted[j] < unsorted[j - 1]: A_ ,A_ = unsorted[j - 1], unsorted[j] A_ = True for j in range(_UpperCamelCase ): if unsorted[j] > unsorted[j + 1]: A_ ,A_ = unsorted[j + 1], unsorted[j] A_ = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() __snake_case : Optional[Any] = input('Enter numbers separated by a comma:\n').strip() __snake_case : Optional[Any] = [int(item) for item in user_input.split(',')] print(F"""{cocktail_shaker_sort(unsorted) = }""")
174
'''simple docstring''' import math def _UpperCAmelCase ( _UpperCamelCase : int ) -> bool: return math.sqrt(_UpperCamelCase ) * math.sqrt(_UpperCamelCase ) == num def _UpperCAmelCase ( _UpperCamelCase : int ) -> bool: A_ = 0 A_ = n while left <= right: A_ = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: A_ = mid - 1 else: A_ = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
174
1
"""simple docstring""" import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): lowercase = True from torch.cuda.amp import autocast lowercase = logging.getLogger(__name__) @dataclass class lowercase__ : '''simple docstring''' _UpperCAmelCase = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}, ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''Whether to log verbose messages or not.'''}, ) _UpperCAmelCase = field( default=2.0, metadata={'''help''': '''Maximum temperature for gumbel softmax.'''} ) _UpperCAmelCase = field( default=0.5, metadata={'''help''': '''Minimum temperature for gumbel softmax.'''} ) _UpperCAmelCase = field( default=0.999995, metadata={'''help''': '''Decay of gumbel temperature during training.'''} ) def UpperCAmelCase ( A : Tuple , A : Dict ): '''simple docstring''' logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) _UpperCAmelCase = logging.WARNING if model_args.verbose_logging: _UpperCAmelCase = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): _UpperCAmelCase = logging.INFO logger.setLevel(lowercase__ ) @dataclass class lowercase__ : '''simple docstring''' _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) _UpperCAmelCase = field( default='''train''', metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' }, ) _UpperCAmelCase = field( default='''validation''', metadata={ '''help''': ( '''The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'''' ) }, ) _UpperCAmelCase = field( default='''file''', metadata={'''help''': '''Column in the dataset that contains speech file path. Defaults to \'file\''''}, ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) _UpperCAmelCase = field( default=1, metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' }, ) _UpperCAmelCase = field( default=__snake_case, metadata={'''help''': '''The number of processes to use for the preprocessing.'''}, ) _UpperCAmelCase = field( default=20.0, metadata={'''help''': '''Filter audio files that are longer than `max_duration_in_seconds` seconds'''} ) @dataclass class lowercase__ : '''simple docstring''' _UpperCAmelCase = 42 _UpperCAmelCase = 42 _UpperCAmelCase = '''longest''' _UpperCAmelCase = None _UpperCAmelCase = None def __call__( self , snake_case ) -> Dict: _UpperCAmelCase = self.feature_extractor.pad( __UpperCamelCase , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) _UpperCAmelCase = self.model._get_feat_extract_output_lengths(batch['input_values'].shape[-1] ) _UpperCAmelCase = batch['input_values'].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula _UpperCAmelCase = self.model._get_feat_extract_output_lengths(batch['attention_mask'].sum(-1 ) ).to( torch.long ) _UpperCAmelCase = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['input_values'].device ) # these two operations makes sure that all values # before the output lengths indices are attended to _UpperCAmelCase = 1 _UpperCAmelCase = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices _UpperCAmelCase = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=__UpperCamelCase , min_masks=2 , ) return batch class lowercase__ ( __snake_case ): '''simple docstring''' def __init__( self , *snake_case , snake_case=1 , snake_case=0 , snake_case=1.0 , **snake_case ) -> List[str]: super().__init__(*__UpperCamelCase , **__UpperCamelCase ) _UpperCAmelCase = 0 _UpperCAmelCase = max_gumbel_temp _UpperCAmelCase = min_gumbel_temp _UpperCAmelCase = gumbel_temp_decay def lowerCamelCase_ ( self , snake_case , snake_case ) -> Optional[int]: model.train() _UpperCAmelCase = self._prepare_inputs(__UpperCamelCase ) if self.use_amp: with autocast(): _UpperCAmelCase = self.compute_loss(__UpperCamelCase , __UpperCamelCase ) else: _UpperCAmelCase = self.compute_loss(__UpperCamelCase , __UpperCamelCase ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": _UpperCAmelCase = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": _UpperCAmelCase = loss.sum() / (inputs['mask_time_indices']).sum() else: raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: _UpperCAmelCase = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__UpperCamelCase ).backward() elif self.use_apex: with amp.scale_loss(__UpperCamelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__UpperCamelCase ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def UpperCAmelCase ( ): '''simple docstring''' _UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = parser.parse_args_into_dataclasses() configure_logger(lowercase__ , lowercase__ ) # Downloading and loading a dataset from the hub. _UpperCAmelCase = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" _UpperCAmelCase = DatasetDict() _UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}[:{data_args.validation_split_percentage}%]' , cache_dir=model_args.cache_dir , ) _UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}[{data_args.validation_split_percentage}%:]' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" _UpperCAmelCase = DatasetDict() _UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='validation' , cache_dir=model_args.cache_dir , ) _UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported _UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=lowercase__ ) def prepare_dataset(A : List[str] ): # check that all files have the correct sampling rate _UpperCAmelCase , _UpperCAmelCase = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays _UpperCAmelCase = datasets.map( lowercase__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['train'].column_names ) # filter audio files that are too long _UpperCAmelCase = vectorized_datasets.filter( lambda A : len(data['speech'] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(A : Tuple ): return feature_extractor(batch['speech'] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` _UpperCAmelCase = vectorized_datasets.map( lowercase__ , batched=lowercase__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['train'].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 _UpperCAmelCase = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( 'PreTraining is only supported for ``config.do_stable_layer_norm=True`` and' ' ``config.feat_extract_norm=\'layer\'' ) _UpperCAmelCase = WavaVecaForPreTraining(lowercase__ ) _UpperCAmelCase = DataCollatorForWavaVecaPretraining(model=lowercase__ , feature_extractor=lowercase__ ) _UpperCAmelCase = WavaVecaPreTrainer( model=lowercase__ , data_collator=lowercase__ , args=lowercase__ , train_dataset=vectorized_datasets['train'] , eval_dataset=vectorized_datasets['validation'] , tokenizer=lowercase__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
573
class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase ): """simple docstring""" snake_case_ = val snake_case_ = None snake_case_ = None def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" if self.val: if val < self.val: if self.left is None: snake_case_ = Node(__UpperCamelCase ) else: self.left.insert(__UpperCamelCase ) elif val > self.val: if self.right is None: snake_case_ = Node(__UpperCamelCase ) else: self.right.insert(__UpperCamelCase ) else: snake_case_ = val def a(lowercase__ , lowercase__ ): '''simple docstring''' # Recursive traversal if root: inorder(root.left , lowercase__ ) res.append(root.val ) inorder(root.right , lowercase__ ) def a(lowercase__ ): '''simple docstring''' # Build BST if len(lowercase__ ) == 0: return arr snake_case_ = Node(arr[0] ) for i in range(1 , len(lowercase__ ) ): root.insert(arr[i] ) # Traverse BST in order. snake_case_ = [] inorder(lowercase__ , lowercase__ ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
187
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __lowerCAmelCase( metaclass=lowerCAmelCase__ ): __snake_case : Union[str, Any] = ['onnx'] def __init__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE : Dict , **SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" requires_backends(self , ['onnx'] ) @classmethod def _lowercase ( cls : List[str] , *SCREAMING_SNAKE_CASE : List[Any] , **SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" requires_backends(cls , ['onnx'] ) @classmethod def _lowercase ( cls : str , *SCREAMING_SNAKE_CASE : List[Any] , **SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" requires_backends(cls , ['onnx'] )
711
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = { """configuration_blip_2""": [ """BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Blip2Config""", """Blip2QFormerConfig""", """Blip2VisionConfig""", ], """processing_blip_2""": ["""Blip2Processor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ """BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Blip2Model""", """Blip2QFormerModel""", """Blip2PreTrainedModel""", """Blip2ForConditionalGeneration""", """Blip2VisionModel""", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
233
0
"""simple docstring""" import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration __lowerCamelCase = { "tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt", "tiny": "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt", "base.en": "https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt", "base": "https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt", "small.en": "https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt", "small": "https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt", "medium.en": "https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt", "medium": "https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt", "large": "https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt", "large-v2": "https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt", } def lowercase ( __UpperCamelCase ) -> Any: __magic_name__ = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) __lowerCamelCase = { "blocks": "layers", "mlp.0": "fc1", "mlp.2": "fc2", "mlp_ln": "final_layer_norm", ".attn.query": ".self_attn.q_proj", ".attn.key": ".self_attn.k_proj", ".attn.value": ".self_attn.v_proj", ".attn_ln": ".self_attn_layer_norm", ".attn.out": ".self_attn.out_proj", ".cross_attn.query": ".encoder_attn.q_proj", ".cross_attn.key": ".encoder_attn.k_proj", ".cross_attn.value": ".encoder_attn.v_proj", ".cross_attn_ln": ".encoder_attn_layer_norm", ".cross_attn.out": ".encoder_attn.out_proj", "decoder.ln.": "decoder.layer_norm.", "encoder.ln.": "encoder.layer_norm.", "token_embedding": "embed_tokens", "encoder.positional_embedding": "encoder.embed_positions.weight", "decoder.positional_embedding": "decoder.embed_positions.weight", "ln_post": "layer_norm", } def lowercase ( __UpperCamelCase ) -> Union[str, Any]: __magic_name__ = list(s_dict.keys() ) for key in keys: __magic_name__ = key for k, v in WHISPER_MAPPING.items(): if k in key: __magic_name__ = new_key.replace(__UpperCamelCase , __UpperCamelCase ) print(f'''{key} -> {new_key}''' ) __magic_name__ = s_dict.pop(__UpperCamelCase ) return s_dict def lowercase ( __UpperCamelCase ) -> Dict: __magic_name__ , __magic_name__ = emb.weight.shape __magic_name__ = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) __magic_name__ = emb.weight.data return lin_layer def lowercase ( __UpperCamelCase , __UpperCamelCase ) -> bytes: os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __magic_name__ = os.path.basename(__UpperCamelCase ) __magic_name__ = url.split('''/''' )[-2] __magic_name__ = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.exists(__UpperCamelCase ) and not os.path.isfile(__UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(__UpperCamelCase ): __magic_name__ = open(__UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(__UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(__UpperCamelCase ) as source, open(__UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=__UpperCamelCase , unit_divisor=1024 ) as loop: while True: __magic_name__ = source.read(8192 ) if not buffer: break output.write(__UpperCamelCase ) loop.update(len(__UpperCamelCase ) ) __magic_name__ = open(__UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(__UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowercase ( __UpperCamelCase , __UpperCamelCase ) -> List[Any]: if ".pt" not in checkpoint_path: __magic_name__ = _download(_MODELS[checkpoint_path] ) else: __magic_name__ = torch.load(__UpperCamelCase , map_location='''cpu''' ) __magic_name__ = original_checkpoint['''dims'''] __magic_name__ = original_checkpoint['''model_state_dict'''] __magic_name__ = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(__UpperCamelCase ) rename_keys(__UpperCamelCase ) __magic_name__ = True __magic_name__ = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] __magic_name__ = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=__UpperCamelCase , decoder_ffn_dim=__UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) __magic_name__ = WhisperForConditionalGeneration(__UpperCamelCase ) __magic_name__ , __magic_name__ = model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) if len(__UpperCamelCase ) > 0 and not set(__UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: __magic_name__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: __magic_name__ = proj_out_weights model.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() # # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Patht to the downloaded checkpoints") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") __lowerCamelCase = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
490
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class _lowercase ( __UpperCAmelCase ): _lowerCamelCase = '''Wav2Vec2FeatureExtractor''' _lowerCamelCase = '''AutoTokenizer''' def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): super().__init__(UpperCamelCase_ , UpperCamelCase_ ) __magic_name__ = self.feature_extractor __magic_name__ = False @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , **UpperCamelCase_ ): try: return super().from_pretrained(UpperCamelCase_ , **UpperCamelCase_ ) except OSError: warnings.warn( f'''Loading a tokenizer inside {cls.__name__} from a config that does not''' ''' include a `tokenizer_class` attribute is deprecated and will be ''' '''removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`''' ''' attribute to either your `config.json` or `tokenizer_config.json` ''' '''file to suppress this warning: ''' , UpperCamelCase_ , ) __magic_name__ = WavaVecaFeatureExtractor.from_pretrained(UpperCamelCase_ , **UpperCamelCase_ ) __magic_name__ = WavaVecaCTCTokenizer.from_pretrained(UpperCamelCase_ , **UpperCamelCase_ ) return cls(feature_extractor=UpperCamelCase_ , tokenizer=UpperCamelCase_ ) def __call__( self , *UpperCamelCase_ , **UpperCamelCase_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*UpperCamelCase_ , **UpperCamelCase_ ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) __magic_name__ = kwargs.pop('''raw_speech''' ) else: __magic_name__ = kwargs.pop('''audio''' , UpperCamelCase_ ) __magic_name__ = kwargs.pop('''sampling_rate''' , UpperCamelCase_ ) __magic_name__ = kwargs.pop('''text''' , UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: __magic_name__ = args[0] __magic_name__ = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: __magic_name__ = self.feature_extractor(UpperCamelCase_ , *UpperCamelCase_ , sampling_rate=UpperCamelCase_ , **UpperCamelCase_ ) if text is not None: __magic_name__ = self.tokenizer(UpperCamelCase_ , **UpperCamelCase_ ) if text is None: return inputs elif audio is None: return encodings else: __magic_name__ = encodings['''input_ids'''] return inputs def lowerCAmelCase__ ( self , *UpperCamelCase_ , **UpperCamelCase_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*UpperCamelCase_ , **UpperCamelCase_ ) __magic_name__ = kwargs.pop('''input_features''' , UpperCamelCase_ ) __magic_name__ = kwargs.pop('''labels''' , UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: __magic_name__ = args[0] __magic_name__ = args[1:] if input_features is not None: __magic_name__ = self.feature_extractor.pad(UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ) if labels is not None: __magic_name__ = self.tokenizer.pad(UpperCamelCase_ , **UpperCamelCase_ ) if labels is None: return input_features elif input_features is None: return labels else: __magic_name__ = labels['''input_ids'''] return input_features def lowerCAmelCase__ ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @contextmanager def lowerCAmelCase__ ( self ): warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) __magic_name__ = True __magic_name__ = self.tokenizer yield __magic_name__ = self.feature_extractor __magic_name__ = False
490
1
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def UpperCAmelCase ( A : np.ndarray , A : np.ndarray , A : np.ndarray , A : int , A : int ): SCREAMING_SNAKE_CASE : str = cva.getAffineTransform(A , A ) return cva.warpAffine(A , A , (rows, cols) ) if __name__ == "__main__": # read original image lowerCAmelCase_ : str = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value lowerCAmelCase_ : int = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape lowerCAmelCase_ : Optional[int] = gray_img.shape # set different points to rotate image lowerCAmelCase_ : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) lowerCAmelCase_ : Any = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) lowerCAmelCase_ : Tuple = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) lowerCAmelCase_ : Optional[int] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list lowerCAmelCase_ : Union[str, Any] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations lowerCAmelCase_ : Optional[int] = plt.figure(1) lowerCAmelCase_ : Optional[Any] = ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3'] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray') plt.title(titles[i]) plt.axis('off') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
701
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": lowerCAmelCase_ : 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') lowerCAmelCase_ : Dict = parser.parse_args() if args.model_type == "roberta": lowerCAmelCase_ : str = RobertaForMaskedLM.from_pretrained(args.model_name) lowerCAmelCase_ : Tuple = 'roberta' elif args.model_type == "gpt2": lowerCAmelCase_ : List[Any] = GPTaLMHeadModel.from_pretrained(args.model_name) lowerCAmelCase_ : Optional[Any] = 'transformer' lowerCAmelCase_ : List[Any] = model.state_dict() lowerCAmelCase_ : List[Any] = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: lowerCAmelCase_ : List[str] = state_dict[f'{prefix}.{param_name}'] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: lowerCAmelCase_ : Any = f'{prefix}.embeddings.{w}.weight' lowerCAmelCase_ : Any = state_dict[param_name] for w in ["weight", "bias"]: lowerCAmelCase_ : str = f'{prefix}.embeddings.LayerNorm.{w}' lowerCAmelCase_ : str = state_dict[param_name] # Transformer Blocks # lowerCAmelCase_ : List[str] = 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"]: lowerCAmelCase_ : List[str] = state_dict[ f'{prefix}.h.{teacher_idx}.{layer}.{w}' ] lowerCAmelCase_ : Any = 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"]: lowerCAmelCase_ : 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"]: lowerCAmelCase_ : List[Any] = state_dict[f'{layer}'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCAmelCase_ : str = state_dict[f'lm_head.dense.{w}'] lowerCAmelCase_ : Optional[int] = state_dict[f'lm_head.layer_norm.{w}'] elif args.model_type == "gpt2": for w in ["weight", "bias"]: lowerCAmelCase_ : Dict = state_dict[f'{prefix}.ln_f.{w}'] lowerCAmelCase_ : Any = 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)
464
0
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def SCREAMING_SNAKE_CASE__ ( __A ) -> Union[str, Any]: _snake_case = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(__A , __A ) def SCREAMING_SNAKE_CASE__ ( __A ) -> Tuple: _snake_case , _snake_case = emb.weight.shape _snake_case = nn.Linear(__A , __A , bias=__A ) _snake_case = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE__ ( __A , __A=None ) -> List[Any]: _snake_case = {} for old_key in state_dict.keys(): _snake_case = old_key if "moe_layer.experts." in key: if expert_idx is not None: _snake_case = key.replace('moe_layer.experts.0' , F'ffn.experts.expert_{expert_idx}' ) else: _snake_case = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: _snake_case = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: _snake_case = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: _snake_case = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: _snake_case = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: _snake_case = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: _snake_case = key.replace('final_layer_norm' , 'ff_layer_norm' ) _snake_case = state_dict[old_key] return new_dict def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A , __A = WEIGHTS_NAME ) -> Optional[int]: _snake_case = [] _snake_case = 0 os.makedirs(__A , exist_ok=__A ) for expert in range(__A ): _snake_case = switch_checkpoint_path + F'-rank-{expert}.pt' if os.path.isfile(__A ): _snake_case = torch.load(__A )['model'] remove_ignore_keys_(__A ) _snake_case = rename_fairseq_keys(__A , __A ) _snake_case = os.path.join( __A , weights_name.replace('.bin' , F'-{len(__A )+1:05d}-of-???.bin' ) ) torch.save(__A , __A ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(__A )[0]].dtype ) # Add the last block _snake_case = os.path.join(__A , weights_name.replace('.bin' , F'-{len(__A )+1:05d}-of-???.bin' ) ) _snake_case = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(__A ) _snake_case = rename_fairseq_keys(__A , __A ) _snake_case = shared_weights['decoder.embed_tokens.weight'] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(__A ) == 1: _snake_case = os.path.join(__A , __A ) torch.save(__A , __A ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(__A , __A ) # Otherwise, let's build the index _snake_case = {} for idx, shard in enumerate(__A ): _snake_case = weights_name.replace('.bin' , F'-{idx+1:05d}-of-{len(__A ):05d}.bin' ) _snake_case = os.path.join(__A , weights_name.replace('.bin' , F'-{idx+1:05d}-of-???.bin' ) ) os.rename(__A , os.path.join(__A , __A ) ) for key in shard: _snake_case = shard_file # Add the metadata _snake_case = {'total_size': total_size} _snake_case = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(__A , __A ) , 'w' , encoding='utf-8' ) as f: _snake_case = json.dumps(__A , indent=2 , sort_keys=__A ) + '\n' f.write(__A ) return metadata, index if __name__ == "__main__": lowercase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--nllb_moe_checkpoint_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b", type=str, required=False, help="Path to the output pytorch model.", ) lowercase : Optional[Any] = parser.parse_args() lowercase , lowercase : Optional[Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) lowercase : List[str] = NllbMoeConfig.from_pretrained( "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) lowercase : Tuple = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("Done") model.save_pretrained(args.pytorch_dump_folder_path)
495
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowercase : str = logging.get_logger(__name__) lowercase : Any = ["model.decoder.embed_positions.weights"] def SCREAMING_SNAKE_CASE__ ( __A ) -> List[Any]: if "emb" in name: _snake_case = name.replace('emb' , 'model.decoder.embed_tokens' ) if "transformer" in name: _snake_case = name.replace('transformer' , 'model.decoder' ) if "cross_attention" in name: _snake_case = name.replace('cross_attention' , 'encoder_attn' ) if "linear1" in name: _snake_case = name.replace('linear1' , 'fc1' ) if "linear2" in name: _snake_case = name.replace('linear2' , 'fc2' ) if "norm1" in name: _snake_case = name.replace('norm1' , 'self_attn_layer_norm' ) if "norm_cross" in name: _snake_case = name.replace('norm_cross' , 'encoder_attn_layer_norm' ) if "norm2" in name: _snake_case = name.replace('norm2' , 'final_layer_norm' ) if "out_norm" in name: _snake_case = name.replace('out_norm' , 'model.decoder.layer_norm' ) if "linears" in name: _snake_case = name.replace('linears' , 'lm_heads' ) if "condition_provider.conditioners.description.output_proj" in name: _snake_case = name.replace('condition_provider.conditioners.description.output_proj' , 'enc_to_dec_proj' ) return name def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> Tuple[Dict, Dict]: _snake_case = list(state_dict.keys() ) _snake_case = {} for key in keys: _snake_case = state_dict.pop(__A ) _snake_case = rename_keys(__A ) if "in_proj_weight" in key: # split fused qkv proj _snake_case = val[:hidden_size, :] _snake_case = val[hidden_size : 2 * hidden_size, :] _snake_case = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _snake_case = val else: _snake_case = val return state_dict, enc_dec_proj_state_dict def SCREAMING_SNAKE_CASE__ ( __A ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values _snake_case = 1_024 _snake_case = 24 _snake_case = 16 elif checkpoint == "medium": _snake_case = 1_536 _snake_case = 48 _snake_case = 24 elif checkpoint == "large": _snake_case = 2_048 _snake_case = 48 _snake_case = 32 else: raise ValueError(F'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) _snake_case = MusicgenDecoderConfig( hidden_size=__A , ffn_dim=hidden_size * 4 , num_hidden_layers=__A , num_attention_heads=__A , ) return config @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( __A , __A=None , __A=None , __A="cpu" ) -> Any: _snake_case = MusicGen.get_pretrained(__A , device=__A ) _snake_case = decoder_config_from_checkpoint(__A ) _snake_case = fairseq_model.lm.state_dict() _snake_case , _snake_case = rename_state_dict( __A , hidden_size=decoder_config.hidden_size ) _snake_case = TaEncoderModel.from_pretrained('t5-base' ) _snake_case = EncodecModel.from_pretrained('facebook/encodec_32khz' ) _snake_case = MusicgenForCausalLM(__A ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _snake_case , _snake_case = decoder.load_state_dict(__A , strict=__A ) for key in missing_keys.copy(): if key.startswith(('text_encoder', 'audio_encoder') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__A ) if len(__A ) > 0: raise ValueError(F'Missing key(s) in state_dict: {missing_keys}' ) if len(__A ) > 0: raise ValueError(F'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model _snake_case = MusicgenForConditionalGeneration(text_encoder=__A , audio_encoder=__A , decoder=__A ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__A ) # check we can do a forward pass _snake_case = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _snake_case = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _snake_case = model(input_ids=__A , decoder_input_ids=__A ).logits if logits.shape != (8, 1, 2_048): raise ValueError('Incorrect shape for logits' ) # now construct the processor _snake_case = AutoTokenizer.from_pretrained('t5-base' ) _snake_case = AutoFeatureExtractor.from_pretrained('facebook/encodec_32khz' , padding_side='left' ) _snake_case = MusicgenProcessor(feature_extractor=__A , tokenizer=__A ) # set the appropriate bos/pad token ids _snake_case = 2_048 _snake_case = 2_048 # set other default generation config params _snake_case = int(30 * audio_encoder.config.frame_rate ) _snake_case = True _snake_case = 3.0 if pytorch_dump_folder is not None: Path(__A ).mkdir(exist_ok=__A ) logger.info(F'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if repo_id: logger.info(F'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(__A ) processor.push_to_hub(__A ) if __name__ == "__main__": lowercase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowercase : List[Any] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
495
1
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class UpperCamelCase( _a ): def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def SCREAMING_SNAKE_CASE_ ( self : str ) -> int: '''simple docstring''' __snake_case = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} return Dataset.from_dict(SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case = self._create_example_records() __snake_case = Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertListEqual(dset.column_names , ["col_1", "col_2"] ) for i, r in enumerate(SCREAMING_SNAKE_CASE ): self.assertDictEqual(SCREAMING_SNAKE_CASE , example_records[i] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case = self._create_example_records() __snake_case = Dataset.from_list(SCREAMING_SNAKE_CASE ) __snake_case = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: # checks what happens with missing columns '''simple docstring''' __snake_case = [{"col_1": 1}, {"col_2": "x"}] __snake_case = Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset[0] , {"col_1": 1} ) self.assertDictEqual(dset[1] , {"col_1": None} ) # NB: first record is used for columns def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[int]: # checks if the type can be inferred from the second record '''simple docstring''' __snake_case = [{"col_1": []}, {"col_1": [1, 2]}] __snake_case = Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertEqual(dset.info.features["col_1"] , Sequence(Value("int64" ) ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case = Dataset.from_list([] ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 0 ) self.assertListEqual(dset.column_names , [] )
473
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def _lowerCAmelCase ( _lowerCAmelCase="" ) -> str: '''simple docstring''' __snake_case = tempfile.mkdtemp() return os.path.join(_lowerCAmelCase , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class UpperCamelCase( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 __snake_case = AgentAudio(SCREAMING_SNAKE_CASE ) __snake_case = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE ) ) # Ensure that the file contains the same value as the original tensor __snake_case , __snake_case = sf.read(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , torch.tensor(SCREAMING_SNAKE_CASE ) , atol=1e-4 ) ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: '''simple docstring''' __snake_case = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 __snake_case = get_new_path(suffix=".wav" ) sf.write(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1_6_0_0_0 ) __snake_case = AgentAudio(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , SCREAMING_SNAKE_CASE ) @require_vision @require_torch class UpperCamelCase( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case = torch.randint(0 , 2_5_6 , (6_4, 6_4, 3) ) __snake_case = AgentImage(SCREAMING_SNAKE_CASE ) __snake_case = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" __snake_case = Image.open(SCREAMING_SNAKE_CASE ) __snake_case = AgentImage(SCREAMING_SNAKE_CASE ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE ) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" __snake_case = Image.open(SCREAMING_SNAKE_CASE ) __snake_case = AgentImage(SCREAMING_SNAKE_CASE ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE ) ) class UpperCamelCase( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: '''simple docstring''' __snake_case = "Hey!" __snake_case = AgentText(SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , agent_type.to_string() ) self.assertEqual(SCREAMING_SNAKE_CASE , agent_type.to_raw() ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
473
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Optional[int] ={ """configuration_xmod""": [ """XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XmodConfig""", """XmodOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Union[str, Any] =[ """XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""", """XmodForCausalLM""", """XmodForMaskedLM""", """XmodForMultipleChoice""", """XmodForQuestionAnswering""", """XmodForSequenceClassification""", """XmodForTokenClassification""", """XmodModel""", """XmodPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowercase : List[Any] =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
364
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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _lowercase : Tuple =logging.get_logger(__name__) class UpperCamelCase_ ( snake_case__ ): _a : List[str] = ['pixel_values'] def __init__( self : List[Any] , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 2_55 , lowerCamelCase : bool = True , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = True , **lowerCamelCase : Optional[Any] , ): super().__init__(**lowerCamelCase ) lowerCamelCase_ : List[Any] = size if size is not None else {'height': 3_84, 'width': 3_84} lowerCamelCase_ : List[str] = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) lowerCamelCase_ : Dict = do_resize lowerCamelCase_ : int = size lowerCamelCase_ : Union[str, Any] = resample lowerCamelCase_ : Tuple = do_rescale lowerCamelCase_ : Dict = rescale_factor lowerCamelCase_ : int = do_normalize lowerCamelCase_ : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCamelCase_ : str = image_std if image_std is not None else OPENAI_CLIP_STD lowerCamelCase_ : int = do_convert_rgb def __a ( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : List[Any] , ): lowerCamelCase_ : List[Any] = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" ) lowerCamelCase_ : Optional[Any] = (size['height'], size['width']) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __a ( self : Union[str, Any] , lowerCamelCase : np.ndarray , lowerCamelCase : Union[int, float] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Union[str, Any] , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __a ( self : str , lowerCamelCase : np.ndarray , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Optional[int] , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __a ( self : List[Any] , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[Dict[str, int]] = None , lowerCamelCase : PILImageResampling = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : bool = None , lowerCamelCase : ChannelDimension = ChannelDimension.FIRST , **lowerCamelCase : Any , ): lowerCamelCase_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ : int = resample if resample is not None else self.resample lowerCamelCase_ : Dict = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ : Any = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ : str = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ : List[str] = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ : str = image_std if image_std is not None else self.image_std lowerCamelCase_ : int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCamelCase_ : Union[str, Any] = size if size is not None else self.size lowerCamelCase_ : Optional[int] = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) lowerCamelCase_ : Dict = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCamelCase_ : int = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. lowerCamelCase_ : List[Any] = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: lowerCamelCase_ : Optional[int] = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_rescale: lowerCamelCase_ : Dict = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: lowerCamelCase_ : Optional[int] = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] lowerCamelCase_ : Optional[int] = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] lowerCamelCase_ : Optional[int] = BatchFeature(data={'pixel_values': images} , tensor_type=lowerCamelCase ) return encoded_outputs
364
1
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 PoolFormerImageProcessor class __A ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple ,_snake_case : Tuple ,_snake_case : List[str]=7 ,_snake_case : Optional[Any]=3 ,_snake_case : List[str]=30 ,_snake_case : List[Any]=400 ,_snake_case : Optional[Any]=True ,_snake_case : int=None ,_snake_case : List[str]=0.9 ,_snake_case : List[Any]=None ,_snake_case : int=True ,_snake_case : Union[str, Any]=[0.5, 0.5, 0.5] ,_snake_case : List[str]=[0.5, 0.5, 0.5] ,) -> int: """simple docstring""" lowercase__ : Union[str, Any] = size if size is not None else {'shortest_edge': 30} lowercase__ : Any = crop_size if crop_size is not None else {'height': 30, 'width': 30} lowercase__ : List[str] = parent lowercase__ : Dict = batch_size lowercase__ : int = num_channels lowercase__ : str = min_resolution lowercase__ : List[str] = max_resolution lowercase__ : Any = do_resize_and_center_crop lowercase__ : List[str] = size lowercase__ : List[Any] = crop_pct lowercase__ : Optional[Any] = crop_size lowercase__ : Optional[Any] = do_normalize lowercase__ : Optional[int] = image_mean lowercase__ : Optional[int] = image_std def UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __A ( a__ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : List[str] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" lowercase__ : List[str] = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase ( self : str ) -> List[Any]: """simple docstring""" lowercase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A ,'''do_resize_and_center_crop''' ) ) self.assertTrue(hasattr(_A ,'''size''' ) ) self.assertTrue(hasattr(_A ,'''crop_pct''' ) ) self.assertTrue(hasattr(_A ,'''do_normalize''' ) ) self.assertTrue(hasattr(_A ,'''image_mean''' ) ) self.assertTrue(hasattr(_A ,'''image_std''' ) ) def UpperCAmelCase ( self : Optional[int] ) -> Any: """simple docstring""" lowercase__ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'''shortest_edge''': 30} ) self.assertEqual(image_processor.crop_size ,{'''height''': 30, '''width''': 30} ) lowercase__ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ,crop_size=84 ) self.assertEqual(image_processor.size ,{'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size ,{'''height''': 84, '''width''': 84} ) def UpperCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" pass def UpperCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" lowercase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ : List[str] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A ,Image.Image ) # Test not batched input lowercase__ : Dict = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowercase__ : Optional[Any] = image_processing(_A ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def UpperCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" lowercase__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__ : Optional[int] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_A ,numpify=_A ) for image in image_inputs: self.assertIsInstance(_A ,np.ndarray ) # Test not batched input lowercase__ : Dict = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowercase__ : Any = image_processing(_A ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def UpperCAmelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" lowercase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_A ,torchify=_A ) for image in image_inputs: self.assertIsInstance(_A ,torch.Tensor ) # Test not batched input lowercase__ : List[str] = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowercase__ : List[Any] = image_processing(_A ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,)
716
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): '''simple docstring''' @slow def UpperCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" lowercase__ : List[str] = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) lowercase__ : Any = { '''input_ids''': tf.convert_to_tensor([[0, 2_646, 10_269, 83, 99_942, 2]] ,dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] ,dtype=tf.intaa ), } lowercase__ : List[Any] = model(_snake_case )['''last_hidden_state'''] lowercase__ : Any = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape ,_snake_case ) # compare the actual values for a slice. lowercase__ : Optional[Any] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] ,dtype=tf.floataa ,) self.assertTrue(np.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
122
0