code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : str = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[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 A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
184
from collections import deque class A : '''simple docstring''' def __init__( self : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> 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 A : '''simple docstring''' def __init__( self : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : list[int] , __lowerCAmelCase : deque[Process] , __lowerCAmelCase : int , ) -> 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 a_ ( self : Dict ) -> list[str]: """simple docstring""" A__ = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def a_ ( self : Tuple , __lowerCAmelCase : list[Process] ) -> list[int]: """simple docstring""" A__ = [] for i in range(len(__lowerCAmelCase ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def a_ ( self : Optional[Any] , __lowerCAmelCase : list[Process] ) -> list[int]: """simple docstring""" A__ = [] for i in range(len(__lowerCAmelCase ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def a_ ( self : Dict , __lowerCAmelCase : list[Process] ) -> list[int]: """simple docstring""" A__ = [] for i in range(len(__lowerCAmelCase ) ): completion_times.append(queue[i].stop_time ) return completion_times def a_ ( self : int , __lowerCAmelCase : deque[Process] ) -> list[int]: """simple docstring""" return [q.burst_time for q in queue] def a_ ( self : Any , __lowerCAmelCase : Process ) -> int: """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def a_ ( self : Union[str, Any] , __lowerCAmelCase : deque[Process] ) -> deque[Process]: """simple docstring""" A__ = deque() # sequence deque of finished process while len(__lowerCAmelCase ) != 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(__lowerCAmelCase ) # 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(__lowerCAmelCase ) self.finish_queue.extend(__lowerCAmelCase ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def a_ ( self : Optional[Any] , __lowerCAmelCase : deque[Process] , __lowerCAmelCase : int ) -> 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(__lowerCAmelCase ) ): 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(__lowerCAmelCase ) # 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(__lowerCAmelCase ) 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(__lowerCAmelCase ) self.finish_queue.extend(__lowerCAmelCase ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def a_ ( self : List[Any] ) -> 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 : Union[str, Any] = Process('''P1''', 0, 5_3) A : Optional[Any] = Process('''P2''', 0, 1_7) A : Optional[int] = Process('''P3''', 0, 6_8) A : int = Process('''P4''', 0, 2_4) A : Any = 3 A : List[Any] = [1_7, 2_5] A : Optional[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 : Optional[Any] = Process('''P1''', 0, 5_3) A : int = Process('''P2''', 0, 1_7) A : Optional[int] = Process('''P3''', 0, 6_8) A : Tuple = Process('''P4''', 0, 2_4) A : Union[str, Any] = 3 A : Optional[Any] = [1_7, 2_5] A : Tuple = deque([Pa, Pa, Pa, Pa]) A : Optional[int] = MLFQ(number_of_queues, time_slices, queue, 0) A : Dict = 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()}''' )
274
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer A_ : int = logging.get_logger(__name__) A_ : List[str] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} A_ : str = { """vocab_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt""" ), """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""", """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli""": ( """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json""" ), }, } A_ : List[Any] = { """squeezebert/squeezebert-uncased""": 5_1_2, """squeezebert/squeezebert-mnli""": 5_1_2, """squeezebert/squeezebert-mnli-headless""": 5_1_2, } A_ : Dict = { """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True}, } class lowercase ( _lowerCamelCase ): """simple docstring""" UpperCAmelCase = VOCAB_FILES_NAMES UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase = SqueezeBertTokenizer def __init__( self ,a_=None ,a_=None ,a_=True ,a_="[UNK]" ,a_="[SEP]" ,a_="[PAD]" ,a_="[CLS]" ,a_="[MASK]" ,a_=True ,a_=None ,**a_ ,) -> Optional[int]: 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_ ,) _UpperCAmelCase : str = 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 ): _UpperCAmelCase : List[Any] = getattr(a_ ,normalizer_state.pop("""type""" ) ) _UpperCAmelCase : Optional[Any] = do_lower_case _UpperCAmelCase : List[Any] = strip_accents _UpperCAmelCase : Optional[Any] = tokenize_chinese_chars _UpperCAmelCase : Tuple = normalizer_class(**a_ ) _UpperCAmelCase : str = do_lower_case def _snake_case ( self ,a_ ,a_=None ) -> int: _UpperCAmelCase : Union[str, Any] = [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 _snake_case ( self ,a_ ,a_ = None ) -> List[int]: _UpperCAmelCase : Union[str, Any] = [self.sep_token_id] _UpperCAmelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self ,a_ ,a_ = None ) -> Tuple[str]: _UpperCAmelCase : str = self._tokenizer.model.save(a_ ,name=a_ ) return tuple(a_ )
353
'''simple docstring''' def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 0 , lowerCAmelCase_ = 0 )-> int: '''simple docstring''' _UpperCAmelCase : Optional[Any] = right or len(lowerCAmelCase_ ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(lowerCAmelCase_ , lowerCAmelCase_ , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
349
0
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 snake_case : Tuple = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class _snake_case ( _snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = SpeechTaTokenizer SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True def SCREAMING_SNAKE_CASE__ ( self ): super().setUp() # We have a SentencePiece fixture for testing a :Dict = SpeechTaTokenizer(__a ) a :str = AddedToken('''<mask>''' , lstrip=__a , rstrip=__a ) a :Optional[Any] = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): a :Any = '''this is a test''' a :str = '''this is a test''' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase=False , _lowerCamelCase=20 , _lowerCamelCase=5 ): a , a :Union[str, Any] = self.get_input_output_texts(__a ) a :int = tokenizer.encode(__a , add_special_tokens=__a ) a :str = tokenizer.decode(__a , clean_up_tokenization_spaces=__a ) return text, ids def SCREAMING_SNAKE_CASE__ ( self ): a :str = '''<pad>''' a :Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def SCREAMING_SNAKE_CASE__ ( self ): a :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(__a ) , 81 ) def SCREAMING_SNAKE_CASE__ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def SCREAMING_SNAKE_CASE__ ( self ): a :str = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): a :Optional[Any] = tokenizer.vocab_size a :Optional[Any] = len(__a ) self.assertNotEqual(__a , 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) a :Any = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] a :Any = tokenizer.add_tokens(__a ) a :str = tokenizer.vocab_size a :str = len(__a ) self.assertNotEqual(__a , 0 ) self.assertEqual(__a , __a ) self.assertEqual(__a , len(__a ) ) self.assertEqual(__a , all_size + len(__a ) ) a :Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__a ) self.assertGreaterEqual(len(__a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) a :List[str] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} a :str = tokenizer.add_special_tokens(__a ) a :Union[str, Any] = tokenizer.vocab_size a :List[Any] = len(__a ) self.assertNotEqual(__a , 0 ) self.assertEqual(__a , __a ) self.assertEqual(__a , len(__a ) ) self.assertEqual(__a , all_size_a + len(__a ) ) a :Union[str, Any] = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__a ) self.assertGreaterEqual(len(__a ) , 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 SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self ): a :Any = self.get_tokenizer() a :str = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__a , [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(__a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) a :Dict = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __a , [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''', '''é''', '''.'''] ) a :Tuple = tokenizer.convert_tokens_to_ids(__a ) # fmt: off self.assertListEqual(__a , [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 a :Union[str, Any] = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [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 SCREAMING_SNAKE_CASE__ ( self ): a :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 a :Tuple = { '''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=__a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__a , )
94
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int: """simple docstring""" if isinstance(__snake_case, torch.Tensor ): return image elif isinstance(__snake_case, PIL.Image.Image ): _UpperCamelCase = [image] if isinstance(image[0], PIL.Image.Image ): _UpperCamelCase = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] _UpperCamelCase = np.concatenate(__snake_case, axis=0 ) _UpperCamelCase = np.array(__snake_case ).astype(np.floataa ) / 255.0 _UpperCamelCase = image.transpose(0, 3, 1, 2 ) _UpperCamelCase = 2.0 * image - 1.0 _UpperCamelCase = torch.from_numpy(__snake_case ) elif isinstance(image[0], torch.Tensor ): _UpperCamelCase = torch.cat(__snake_case, dim=0 ) return image def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=0.9995 ) -> List[Any]: """simple docstring""" if not isinstance(__snake_case, np.ndarray ): _UpperCamelCase = True _UpperCamelCase = va.device _UpperCamelCase = va.cpu().numpy() _UpperCamelCase = va.cpu().numpy() _UpperCamelCase = np.sum(va * va / (np.linalg.norm(__snake_case ) * np.linalg.norm(__snake_case )) ) if np.abs(__snake_case ) > DOT_THRESHOLD: _UpperCamelCase = (1 - t) * va + t * va else: _UpperCamelCase = np.arccos(__snake_case ) _UpperCamelCase = np.sin(__snake_case ) _UpperCamelCase = theta_a * t _UpperCamelCase = np.sin(__snake_case ) _UpperCamelCase = np.sin(theta_a - theta_t ) / sin_theta_a _UpperCamelCase = sin_theta_t / sin_theta_a _UpperCamelCase = sa * va + sa * va if inputs_are_torch: _UpperCamelCase = torch.from_numpy(__snake_case ).to(__snake_case ) return va def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]: """simple docstring""" _UpperCamelCase = F.normalize(__snake_case, dim=-1 ) _UpperCamelCase = F.normalize(__snake_case, dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" for param in model.parameters(): _UpperCamelCase = value class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a , __a , __a , __a , __a , __a , __a , __a=None , __a=None , __a=None , ) -> List[str]: '''simple docstring''' super().__init__() self.register_modules( vae=__a , text_encoder=__a , clip_model=__a , tokenizer=__a , unet=__a , scheduler=__a , feature_extractor=__a , coca_model=__a , coca_tokenizer=__a , coca_transform=__a , ) _UpperCamelCase = ( feature_extractor.size if isinstance(feature_extractor.size , __a) else feature_extractor.size['''shortest_edge'''] ) _UpperCamelCase = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std) set_requires_grad(self.text_encoder , __a) set_requires_grad(self.clip_model , __a) def UpperCAmelCase ( self , __a = "auto") -> Union[str, Any]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a) def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' self.enable_attention_slicing(__a) def UpperCAmelCase ( self) -> int: '''simple docstring''' set_requires_grad(self.vae , __a) def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' set_requires_grad(self.vae , __a) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' set_requires_grad(self.unet , __a) def UpperCAmelCase ( self) -> int: '''simple docstring''' set_requires_grad(self.unet , __a) def UpperCAmelCase ( self , __a , __a , __a) -> Any: '''simple docstring''' # get the original timestep using init_timestep _UpperCamelCase = min(int(num_inference_steps * strength) , __a) _UpperCamelCase = max(num_inference_steps - init_timestep , 0) _UpperCamelCase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a=None) -> Tuple: '''simple docstring''' if not isinstance(__a , torch.Tensor): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(__a)}''') _UpperCamelCase = image.to(device=__a , dtype=__a) if isinstance(__a , __a): _UpperCamelCase = [ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(__a) ] _UpperCamelCase = torch.cat(__a , dim=0) else: _UpperCamelCase = self.vae.encode(__a).latent_dist.sample(__a) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 0.1_8215 * init_latents _UpperCamelCase = init_latents.repeat_interleave(__a , dim=0) _UpperCamelCase = randn_tensor(init_latents.shape , generator=__a , device=__a , dtype=__a) # get latents _UpperCamelCase = self.scheduler.add_noise(__a , __a , __a) _UpperCamelCase = init_latents return latents def UpperCAmelCase ( self , __a) -> str: '''simple docstring''' _UpperCamelCase = self.coca_transform(__a).unsqueeze(0) with torch.no_grad(), torch.cuda.amp.autocast(): _UpperCamelCase = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype)) _UpperCamelCase = self.coca_tokenizer.decode(generated[0].cpu().numpy()) return generated.split('''<end_of_text>''')[0].replace('''<start_of_text>''' , '''''').rstrip(''' .,''') def UpperCAmelCase ( self , __a , __a) -> Optional[int]: '''simple docstring''' _UpperCamelCase = self.feature_extractor.preprocess(__a) _UpperCamelCase = torch.from_numpy(clip_image_input['''pixel_values'''][0]).unsqueeze(0).to(self.device).half() _UpperCamelCase = self.clip_model.get_image_features(__a) _UpperCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__a) _UpperCamelCase = image_embeddings_clip.repeat_interleave(__a , dim=0) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ) -> Tuple: '''simple docstring''' _UpperCamelCase = latents.detach().requires_grad_() _UpperCamelCase = self.scheduler.scale_model_input(__a , __a) # predict the noise residual _UpperCamelCase = self.unet(__a , __a , encoder_hidden_states=__a).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)): _UpperCamelCase = self.scheduler.alphas_cumprod[timestep] _UpperCamelCase = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCamelCase = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 _UpperCamelCase = torch.sqrt(__a) _UpperCamelCase = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __a): _UpperCamelCase = self.scheduler.sigmas[index] _UpperCamelCase = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler)} not supported''') # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 1 / 0.1_8215 * sample _UpperCamelCase = self.vae.decode(__a).sample _UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1) _UpperCamelCase = transforms.Resize(self.feature_extractor_size)(__a) _UpperCamelCase = self.normalize(__a).to(latents.dtype) _UpperCamelCase = self.clip_model.get_image_features(__a) _UpperCamelCase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__a) _UpperCamelCase = spherical_dist_loss(__a , __a).mean() * clip_guidance_scale _UpperCamelCase = -torch.autograd.grad(__a , __a)[0] if isinstance(self.scheduler , __a): _UpperCamelCase = latents.detach() + grads * (sigma**2) _UpperCamelCase = noise_pred_original else: _UpperCamelCase = noise_pred_original - torch.sqrt(__a) * grads return noise_pred, latents @torch.no_grad() def __call__( self , __a , __a , __a = None , __a = None , __a = 5_12 , __a = 5_12 , __a = 0.6 , __a = 50 , __a = 7.5 , __a = 1 , __a = 0.0 , __a = 1_00 , __a = None , __a = "pil" , __a = True , __a = 0.8 , __a = 0.1 , __a = 0.1 , ) -> Dict: '''simple docstring''' if isinstance(__a , __a) and len(__a) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(__a)} generators.''') if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''') if isinstance(__a , torch.Generator) and batch_size > 1: _UpperCamelCase = [generator] + [None] * (batch_size - 1) _UpperCamelCase = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] _UpperCamelCase = [x[0] for x in coca_is_none if x[1]] _UpperCamelCase = ''', '''.join(__a) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__a): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''') _UpperCamelCase = self.get_image_description(__a) if style_prompt is None: if len(__a): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''') _UpperCamelCase = self.get_image_description(__a) # get prompt text embeddings for content and style _UpperCamelCase = self.tokenizer( __a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase = self.text_encoder(content_text_input.input_ids.to(self.device))[0] _UpperCamelCase = self.tokenizer( __a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase = self.text_encoder(style_text_input.input_ids.to(self.device))[0] _UpperCamelCase = slerp(__a , __a , __a) # duplicate text embeddings for each generation per prompt _UpperCamelCase = text_embeddings.repeat_interleave(__a , dim=0) # set timesteps _UpperCamelCase = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys()) _UpperCamelCase = {} if accepts_offset: _UpperCamelCase = 1 self.scheduler.set_timesteps(__a , **__a) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device) _UpperCamelCase , _UpperCamelCase = self.get_timesteps(__a , __a , self.device) _UpperCamelCase = timesteps[:1].repeat(__a) # Preprocess image _UpperCamelCase = preprocess(__a , __a , __a) _UpperCamelCase = self.prepare_latents( __a , __a , __a , text_embeddings.dtype , self.device , __a) _UpperCamelCase = preprocess(__a , __a , __a) _UpperCamelCase = self.prepare_latents( __a , __a , __a , text_embeddings.dtype , self.device , __a) _UpperCamelCase = slerp(__a , __a , __a) if clip_guidance_scale > 0: _UpperCamelCase = self.get_clip_image_embeddings(__a , __a) _UpperCamelCase = self.get_clip_image_embeddings(__a , __a) _UpperCamelCase = slerp( __a , __a , __a) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _UpperCamelCase = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _UpperCamelCase = content_text_input.input_ids.shape[-1] _UpperCamelCase = self.tokenizer([''''''] , padding='''max_length''' , max_length=__a , return_tensors='''pt''') _UpperCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt _UpperCamelCase = uncond_embeddings.repeat_interleave(__a , dim=0) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _UpperCamelCase = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _UpperCamelCase = (batch_size, self.unet.config.in_channels, height // 8, width // 8) _UpperCamelCase = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps _UpperCamelCase = torch.randn(__a , generator=__a , device='''cpu''' , dtype=__a).to( self.device) else: _UpperCamelCase = torch.randn(__a , generator=__a , device=self.device , dtype=__a) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''') _UpperCamelCase = latents.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _UpperCamelCase = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _UpperCamelCase = '''eta''' in set(inspect.signature(self.scheduler.step).parameters.keys()) _UpperCamelCase = {} if accepts_eta: _UpperCamelCase = eta # check if the scheduler accepts generator _UpperCamelCase = '''generator''' in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: _UpperCamelCase = generator with self.progress_bar(total=__a): for i, t in enumerate(__a): # expand the latents if we are doing classifier free guidance _UpperCamelCase = torch.cat([latents] * 2) if do_classifier_free_guidance else latents _UpperCamelCase = self.scheduler.scale_model_input(__a , __a) # predict the noise residual _UpperCamelCase = self.unet(__a , __a , encoder_hidden_states=__a).sample # perform classifier free guidance if do_classifier_free_guidance: _UpperCamelCase , _UpperCamelCase = noise_pred.chunk(2) _UpperCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: _UpperCamelCase = ( text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings ) _UpperCamelCase , _UpperCamelCase = self.cond_fn( __a , __a , __a , __a , __a , __a , __a , ) # compute the previous noisy sample x_t -> x_t-1 _UpperCamelCase = self.scheduler.step(__a , __a , __a , **__a).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCamelCase = 1 / 0.1_8215 * latents _UpperCamelCase = self.vae.decode(__a).sample _UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1) _UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": _UpperCamelCase = self.numpy_to_pil(__a) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__a , nsfw_content_detected=__a)
194
0
"""simple docstring""" import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='''session''') def lowerCamelCase () -> Optional[int]: lowercase :Optional[Any] = 10 lowercase :int = datasets.Features( { '''tokens''': datasets.Sequence(datasets.Value('''string''')), '''labels''': datasets.Sequence(datasets.ClassLabel(names=['''negative''', '''positive'''])), '''answers''': datasets.Sequence( { '''text''': datasets.Value('''string'''), '''answer_start''': datasets.Value('''int32'''), }), '''id''': datasets.Value('''int64'''), }) lowercase :List[str] = datasets.Dataset.from_dict( { '''tokens''': [['''foo'''] * 5] * n, '''labels''': [[1] * 5] * n, '''answers''': [{'''answer_start''': [97], '''text''': ['''1976''']}] * 10, '''id''': list(range(a_)), } , features=a_ , ) return dataset @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[int] , a_ :Dict) -> Union[str, Any]: lowercase :Any = str(tmp_path_factory.mktemp('''data''') / '''file.arrow''') dataset.map(cache_file_name=a_) return filename # FILE_CONTENT + files UpperCAmelCase = '''\\n Text data.\n Second line of data.''' @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Dict) -> Tuple: lowercase :Dict = tmp_path_factory.mktemp('''data''') / "file.txt" lowercase :Tuple = FILE_CONTENT with open(a_ , '''w''') as f: f.write(a_) return filename @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Union[str, Any]: import bza lowercase :str = tmp_path_factory.mktemp('''data''') / "file.txt.bz2" lowercase :Optional[int] = bytes(a_ , '''utf-8''') with bza.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]: import gzip lowercase :str = str(tmp_path_factory.mktemp('''data''') / '''file.txt.gz''') lowercase :Any = bytes(a_ , '''utf-8''') with gzip.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :str) -> List[str]: if datasets.config.LZ4_AVAILABLE: import lza.frame lowercase :Optional[int] = tmp_path_factory.mktemp('''data''') / "file.txt.lz4" lowercase :str = bytes(a_ , '''utf-8''') with lza.frame.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :int , a_ :Any) -> List[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr lowercase :Any = tmp_path_factory.mktemp('''data''') / "file.txt.7z" with pyazr.SevenZipFile(a_ , '''w''') as archive: archive.write(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any , a_ :List[str]) -> List[str]: import tarfile lowercase :Union[str, Any] = tmp_path_factory.mktemp('''data''') / "file.txt.tar" with tarfile.TarFile(a_ , '''w''') as f: f.add(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :int) -> List[str]: import lzma lowercase :List[Any] = tmp_path_factory.mktemp('''data''') / "file.txt.xz" lowercase :List[str] = bytes(a_ , '''utf-8''') with lzma.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Dict , a_ :Tuple) -> Optional[Any]: import zipfile lowercase :Tuple = tmp_path_factory.mktemp('''data''') / "file.txt.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[int]) -> Optional[Any]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd lowercase :Optional[int] = tmp_path_factory.mktemp('''data''') / "file.txt.zst" lowercase :int = bytes(a_ , '''utf-8''') with zstd.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[int]) -> int: lowercase :List[str] = tmp_path_factory.mktemp('''data''') / "file.xml" lowercase :Tuple = textwrap.dedent( '''\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>''') with open(a_ , '''w''') as f: f.write(a_) return filename UpperCAmelCase = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] UpperCAmelCase = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] UpperCAmelCase = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } UpperCAmelCase = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] UpperCAmelCase = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope='''session''') def lowerCamelCase () -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Tuple: lowercase :str = datasets.Dataset.from_dict(a_) lowercase :Optional[int] = str(tmp_path_factory.mktemp('''data''') / '''dataset.arrow''') dataset.map(cache_file_name=a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :str) -> List[str]: lowercase :int = str(tmp_path_factory.mktemp('''data''') / '''dataset.sqlite''') with contextlib.closing(sqlitea.connect(a_)) as con: lowercase :List[Any] = con.cursor() cur.execute('''CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)''') for item in DATA: cur.execute('''INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)''' , tuple(item.values())) con.commit() return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any) -> List[Any]: lowercase :Dict = str(tmp_path_factory.mktemp('''data''') / '''dataset.csv''') with open(a_ , '''w''' , newline='''''') as f: lowercase :Dict = csv.DictWriter(a_ , fieldnames=['''col_1''', '''col_2''', '''col_3''']) writer.writeheader() for item in DATA: writer.writerow(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]: lowercase :Union[str, Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset2.csv''') with open(a_ , '''w''' , newline='''''') as f: lowercase :Optional[int] = csv.DictWriter(a_ , fieldnames=['''col_1''', '''col_2''', '''col_3''']) writer.writeheader() for item in DATA: writer.writerow(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :str , a_ :str) -> str: import bza lowercase :str = tmp_path_factory.mktemp('''data''') / "dataset.csv.bz2" with open(a_ , '''rb''') as f: lowercase :Any = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(a_ , '''wb''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[int] , a_ :Dict , a_ :Optional[int]) -> List[str]: lowercase :List[Any] = tmp_path_factory.mktemp('''data''') / "dataset.csv.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(a_)) f.write(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :List[str] , a_ :Union[str, Any] , a_ :int) -> Optional[Any]: lowercase :int = tmp_path_factory.mktemp('''data''') / "dataset.csv.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(csv_path.replace('''.csv''' , '''.CSV'''))) f.write(a_ , arcname=os.path.basename(csva_path.replace('''.csv''' , '''.CSV'''))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any , a_ :Union[str, Any] , a_ :Tuple) -> str: lowercase :Any = tmp_path_factory.mktemp('''data''') / "dataset_with_dir.csv.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Tuple) -> Union[str, Any]: lowercase :Optional[Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset.parquet''') lowercase :Dict = pa.schema( { '''col_1''': pa.string(), '''col_2''': pa.intaa(), '''col_3''': pa.floataa(), }) with open(a_ , '''wb''') as f: lowercase :Tuple = pq.ParquetWriter(a_ , schema=a_) lowercase :Tuple = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(a_))] for k in DATA[0]} , schema=a_) writer.write_table(a_) writer.close() return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any) -> Optional[int]: lowercase :Union[str, Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset.json''') lowercase :str = {"data": DATA} with open(a_ , '''w''') as f: json.dump(a_ , a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Union[str, Any]: lowercase :Optional[int] = str(tmp_path_factory.mktemp('''data''') / '''dataset.json''') lowercase :Dict = {"data": DATA_DICT_OF_LISTS} with open(a_ , '''w''') as f: json.dump(a_ , a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :int) -> Any: lowercase :Optional[Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset.jsonl''') with open(a_ , '''w''') as f: for item in DATA: f.write(json.dumps(a_) + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Tuple) -> Tuple: lowercase :Any = str(tmp_path_factory.mktemp('''data''') / '''dataset2.jsonl''') with open(a_ , '''w''') as f: for item in DATA: f.write(json.dumps(a_) + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any) -> List[str]: lowercase :int = str(tmp_path_factory.mktemp('''data''') / '''dataset_312.jsonl''') with open(a_ , '''w''') as f: for item in DATA_312: f.write(json.dumps(a_) + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[Any]) -> Optional[Any]: lowercase :Optional[int] = str(tmp_path_factory.mktemp('''data''') / '''dataset-str.jsonl''') with open(a_ , '''w''') as f: for item in DATA_STR: f.write(json.dumps(a_) + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any] , a_ :Any) -> str: import gzip lowercase :Optional[Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset.txt.gz''') with open(a_ , '''rb''') as orig_file: with gzip.open(a_ , '''wb''') as zipped_file: zipped_file.writelines(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[Any] , a_ :Tuple) -> List[Any]: import gzip lowercase :List[Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset.jsonl.gz''') with open(a_ , '''rb''') as orig_file: with gzip.open(a_ , '''wb''') as zipped_file: zipped_file.writelines(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Dict , a_ :List[Any] , a_ :Union[str, Any]) -> Union[str, Any]: lowercase :Tuple = tmp_path_factory.mktemp('''data''') / "dataset.jsonl.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(a_)) f.write(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any] , a_ :Optional[int] , a_ :Optional[Any] , a_ :Dict) -> Optional[int]: lowercase :Dict = tmp_path_factory.mktemp('''data''') / "dataset_nested.jsonl.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.join('''nested''' , os.path.basename(a_))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :List[Any] , a_ :Optional[int] , a_ :List[str]) -> List[str]: lowercase :Dict = tmp_path_factory.mktemp('''data''') / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :List[Any] , a_ :List[Any] , a_ :str) -> Any: lowercase :Optional[Any] = tmp_path_factory.mktemp('''data''') / "dataset.jsonl.tar" with tarfile.TarFile(a_ , '''w''') as f: f.add(a_ , arcname=os.path.basename(a_)) f.add(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :List[str] , a_ :List[Any] , a_ :Tuple , a_ :Dict) -> Dict: lowercase :List[Any] = tmp_path_factory.mktemp('''data''') / "dataset_nested.jsonl.tar" with tarfile.TarFile(a_ , '''w''') as f: f.add(a_ , arcname=os.path.join('''nested''' , os.path.basename(a_))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :List[str]) -> int: lowercase :List[str] = ["0", "1", "2", "3"] lowercase :Tuple = str(tmp_path_factory.mktemp('''data''') / '''dataset.txt''') with open(a_ , '''w''') as f: for item in data: f.write(item + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Union[str, Any]) -> Dict: lowercase :Dict = ["0", "1", "2", "3"] lowercase :Optional[Any] = str(tmp_path_factory.mktemp('''data''') / '''dataset2.txt''') with open(a_ , '''w''') as f: for item in data: f.write(item + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any) -> Tuple: lowercase :int = ["0", "1", "2", "3"] lowercase :str = tmp_path_factory.mktemp('''data''') / "dataset.abc" with open(a_ , '''w''') as f: for item in data: f.write(item + '''\n''') return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[Any] , a_ :Any , a_ :Union[str, Any]) -> List[Any]: lowercase :Union[str, Any] = tmp_path_factory.mktemp('''data''') / "dataset.text.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(a_)) f.write(a_ , arcname=os.path.basename(a_)) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[int] , a_ :List[Any] , a_ :List[Any]) -> Union[str, Any]: lowercase :List[Any] = tmp_path_factory.mktemp('''data''') / "dataset_with_dir.text.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) f.write(a_ , arcname=os.path.join('''main_dir''' , os.path.basename(a_))) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Any , a_ :str , a_ :Tuple) -> int: lowercase :List[Any] = tmp_path_factory.mktemp('''data''') / "dataset.ext.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename('''unsupported.ext''')) f.write(a_ , arcname=os.path.basename('''unsupported_2.ext''')) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Optional[Any]) -> Any: lowercase :List[str] = "\n".join(['''First''', '''Second\u2029with Unicode new line''', '''Third''']) lowercase :str = str(tmp_path_factory.mktemp('''data''') / '''dataset_with_unicode_new_lines.txt''') with open(a_ , '''w''' , encoding='''utf-8''') as f: f.write(a_) return path @pytest.fixture(scope='''session''') def lowerCamelCase () -> Tuple: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_image_rgb.jpg''') @pytest.fixture(scope='''session''') def lowerCamelCase () -> Optional[Any]: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_audio_44100.wav''') @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :int , a_ :Optional[Any]) -> Union[str, Any]: lowercase :Union[str, Any] = tmp_path_factory.mktemp('''data''') / "dataset.img.zip" with zipfile.ZipFile(a_ , '''w''') as f: f.write(a_ , arcname=os.path.basename(a_)) f.write(a_ , arcname=os.path.basename(a_).replace('''.jpg''' , '''2.jpg''')) return path @pytest.fixture(scope='''session''') def lowerCamelCase (a_ :Tuple) -> List[str]: lowercase :Optional[Any] = tmp_path_factory.mktemp('''data_dir''') (data_dir / "subdir").mkdir() with open(data_dir / '''subdir''' / '''train.txt''' , '''w''') as f: f.write('''foo\n''' * 10) with open(data_dir / '''subdir''' / '''test.txt''' , '''w''') as f: f.write('''bar\n''' * 10) # hidden file with open(data_dir / '''subdir''' / '''.test.txt''' , '''w''') as f: f.write('''bar\n''' * 10) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '''.subdir''' / '''train.txt''' , '''w''') as f: f.write('''foo\n''' * 10) with open(data_dir / '''.subdir''' / '''test.txt''' , '''w''') as f: f.write('''bar\n''' * 10) return data_dir
367
"""simple docstring""" def lowerCamelCase (a_ :int) -> None: lowercase :Tuple = generate_pascal_triangle(a_) for row_idx in range(a_): # 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 lowerCamelCase (a_ :int) -> list[list[int]]: if not isinstance(a_ , a_): 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''') lowercase :list[list[int]] = [] for current_row_idx in range(a_): lowercase :Union[str, Any] = populate_current_row(a_ , a_) triangle.append(a_) return triangle def lowerCamelCase (a_ :list[list[int]] , a_ :int) -> list[int]: lowercase :List[str] = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 lowercase , lowercase :Dict = 1, 1 for current_col_idx in range(1 , a_): calculate_current_element( a_ , a_ , a_ , a_) return current_row def lowerCamelCase (a_ :list[list[int]] , a_ :list[int] , a_ :int , a_ :int , ) -> None: lowercase :str = triangle[current_row_idx - 1][current_col_idx - 1] lowercase :Dict = triangle[current_row_idx - 1][current_col_idx] lowercase :Any = above_to_left_elt + above_to_right_elt def lowerCamelCase (a_ :int) -> list[list[int]]: if not isinstance(a_ , a_): 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''') lowercase :list[list[int]] = [[1]] for row_index in range(1 , a_): lowercase :Union[str, Any] = [0] + result[-1] + [0] lowercase :Union[str, Any] = row_index + 1 # Calculate the number of distinct elements in a row lowercase :List[str] = sum(divmod(a_ , 2)) lowercase :Dict = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1) ] lowercase :Optional[int] = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() lowercase :Dict = row_first_half + row_second_half result.append(a_) return result def lowerCamelCase () -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(a_ :Callable , a_ :int) -> None: lowercase :int = F"""{func.__name__}({value})""" lowercase :Union[str, 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(15): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(a_ , a_) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
172
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __lowerCAmelCase : Optional[Any] ='__DUMMY_TRANSFORMERS_USER__' __lowerCAmelCase : Dict ='Dummy User' __lowerCAmelCase : Tuple ='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' __lowerCAmelCase : str ='https://hub-ci.huggingface.co' __lowerCAmelCase : List[Any] =CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}' __lowerCAmelCase : Dict =CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}' __lowerCAmelCase : Optional[int] =Path('~/.huggingface/hub_ci_token').expanduser() @pytest.fixture def _UpperCamelCase ( lowercase__ ): monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''' , lowercase__ ) @pytest.fixture def _UpperCamelCase ( lowercase__ ): monkeypatch.setattr('''datasets.config.HF_ENDPOINT''' , lowercase__ ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''' , lowercase__ ) @pytest.fixture def _UpperCamelCase ( lowercase__ ): monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''' , lowercase__ ) @pytest.fixture def _UpperCamelCase ( lowercase__ , lowercase__ ): HfFolder.save_token(lowercase__ ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def _UpperCamelCase ( ): return HfApi(endpoint=lowercase__ ) @pytest.fixture(scope='''session''' ) def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = HfFolder.get_token() HfFolder.save_token(lowercase__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(lowercase__ ) @pytest.fixture def _UpperCamelCase ( lowercase__ ): def _cleanup_repo(lowercase__ ): hf_api.delete_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def _UpperCamelCase ( lowercase__ ): @contextmanager def _temporary_repo(lowercase__ ): try: yield repo_id finally: cleanup_repo(lowercase__ ) return _temporary_repo @pytest.fixture(scope='''session''' ) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Dict = F'''repo_txt_data-{int(time.time() * 10e3 )}''' __SCREAMING_SNAKE_CASE : Optional[int] = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' , private=lowercase__ ) hf_api.upload_file( token=lowercase__ , path_or_fileobj=str(lowercase__ ) , path_in_repo='''data/text_data.txt''' , repo_id=lowercase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : List[Any] = F'''repo_zipped_txt_data-{int(time.time() * 10e3 )}''' __SCREAMING_SNAKE_CASE : Optional[Any] = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' , private=lowercase__ ) hf_api.upload_file( token=lowercase__ , path_or_fileobj=str(lowercase__ ) , path_in_repo='''data.zip''' , repo_id=lowercase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Dict = F'''repo_zipped_img_data-{int(time.time() * 10e3 )}''' __SCREAMING_SNAKE_CASE : List[str] = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' , private=lowercase__ ) hf_api.upload_file( token=lowercase__ , path_or_fileobj=str(lowercase__ ) , path_in_repo='''data.zip''' , repo_id=lowercase__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(lowercase__ , token=lowercase__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): return hf_private_dataset_repo_zipped_img_data_
9
class A : """simple docstring""" def __init__( self : Any,lowercase_ : Tuple,lowercase_ : Any,lowercase_ : List[str] )-> List[Any]: '''simple docstring''' A__ = name A__ = value A__ = weight def __repr__( self : int )-> Tuple: '''simple docstring''' return F'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def snake_case__ ( self : Any )-> str: '''simple docstring''' return self.value def snake_case__ ( self : Any )-> Tuple: '''simple docstring''' return self.name def snake_case__ ( self : Any )-> Dict: '''simple docstring''' return self.weight def snake_case__ ( self : Union[str, Any] )-> Optional[Any]: '''simple docstring''' return self.value / self.weight def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: '''simple docstring''' A__ = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _snake_case( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> Any: '''simple docstring''' A__ = sorted(SCREAMING_SNAKE_CASE__ , key=SCREAMING_SNAKE_CASE__ , reverse=SCREAMING_SNAKE_CASE__ ) A__ = [] A__ , A__ = 0.0, 0.0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _snake_case( ) -> Any: '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
7
0
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __UpperCAmelCase = 16 __UpperCAmelCase = 32 def __UpperCamelCase ( lowercase__ : Dict ) -> Dict: '''simple docstring''' return int(x / 2**20 ) class __a : def __enter__( self : List[str] ): gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero lowerCAmelCase_ : Union[str, Any] = torch.cuda.memory_allocated() return self def __exit__( self : Optional[Any] , *UpperCAmelCase : str ): gc.collect() torch.cuda.empty_cache() lowerCAmelCase_ : List[Any] = torch.cuda.memory_allocated() lowerCAmelCase_ : Dict = torch.cuda.max_memory_allocated() lowerCAmelCase_ : Optional[int] = bamb(self.end - self.begin ) lowerCAmelCase_ : Any = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def __UpperCamelCase ( lowercase__ : Accelerator , lowercase__ : int = 16 , lowercase__ : str = "bert-base-cased" , lowercase__ : int = 320 , lowercase__ : int = 160 , ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ : Union[str, Any] = AutoTokenizer.from_pretrained(lowercase__ ) lowerCAmelCase_ : Dict = load_dataset( """glue""" , """mrpc""" , split={"""train""": f'train[:{n_train}]', """validation""": f'validation[:{n_val}]'} ) def tokenize_function(lowercase__ : int ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase_ : int = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase__ , max_length=lowercase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCAmelCase_ : Any = datasets.map( lowercase__ , batched=lowercase__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=lowercase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase_ : Dict = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowercase__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowercase__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. lowerCAmelCase_ : List[Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) lowerCAmelCase_ : int = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) return train_dataloader, eval_dataloader def __UpperCamelCase ( lowercase__ : Any , lowercase__ : str ) -> int: '''simple docstring''' lowerCAmelCase_ : int = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase_ : Any = config["""lr"""] lowerCAmelCase_ : Dict = int(config["""num_epochs"""] ) lowerCAmelCase_ : int = int(config["""seed"""] ) lowerCAmelCase_ : Optional[Any] = int(config["""batch_size"""] ) lowerCAmelCase_ : Union[str, Any] = args.model_name_or_path set_seed(lowercase__ ) lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = get_dataloaders(lowercase__ , lowercase__ , lowercase__ , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(lowercase__ , return_dict=lowercase__ ) # Instantiate optimizer lowerCAmelCase_ : Tuple = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCAmelCase_ : List[Any] = optimizer_cls(params=model.parameters() , lr=lowercase__ ) if accelerator.state.deepspeed_plugin is not None: lowerCAmelCase_ : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: lowerCAmelCase_ : int = 1 lowerCAmelCase_ : Dict = (len(lowercase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCAmelCase_ : List[Any] = get_linear_schedule_with_warmup( optimizer=lowercase__ , num_warmup_steps=0 , num_training_steps=lowercase__ , ) else: lowerCAmelCase_ : Tuple = DummyScheduler(lowercase__ , total_num_steps=lowercase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) # We need to keep track of how many total steps we have iterated over lowerCAmelCase_ : int = 0 # We also need to keep track of the stating epoch so files are named properly lowerCAmelCase_ : List[str] = 0 # Now we train the model lowerCAmelCase_ : int = {} for epoch in range(lowercase__ , lowercase__ ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(lowercase__ ): lowerCAmelCase_ : Union[str, Any] = model(**lowercase__ ) lowerCAmelCase_ : Union[str, Any] = outputs.loss lowerCAmelCase_ : int = loss / gradient_accumulation_steps accelerator.backward(lowercase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("""Memory before entering the train : {}""".format(bamb(tracemalloc.begin ) ) ) accelerator.print("""Memory consumed at the end of the train (end-begin): {}""".format(tracemalloc.used ) ) accelerator.print("""Peak Memory consumed during the train (max-begin): {}""".format(tracemalloc.peaked ) ) accelerator.print( """Total Peak Memory consumed during the train (max): {}""".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) lowerCAmelCase_ : Any = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[f'epoch-{epoch}'] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """peak_memory_utilization.json""" ) , """w""" ) as f: json.dump(lowercase__ , lowercase__ ) def __UpperCamelCase ( ) -> List[Any]: '''simple docstring''' lowerCAmelCase_ : List[Any] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=lowercase__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=lowercase__ , ) parser.add_argument( """--output_dir""" , type=lowercase__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--peak_memory_upper_bound""" , type=lowercase__ , default=lowercase__ , help="""The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.""" , ) parser.add_argument( """--n_train""" , type=lowercase__ , default=320 , help="""Number of training examples to use.""" , ) parser.add_argument( """--n_val""" , type=lowercase__ , default=160 , help="""Number of validation examples to use.""" , ) parser.add_argument( """--num_epochs""" , type=lowercase__ , default=1 , help="""Number of train epochs.""" , ) lowerCAmelCase_ : List[str] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowercase__ , lowercase__ ) if __name__ == "__main__": main()
354
from __future__ import annotations from typing import Any class __a : def __init__( self : Dict , UpperCAmelCase : int = 6 ): lowerCAmelCase_ : Node | None = None lowerCAmelCase_ : Node | None = None self.create_linked_list(UpperCAmelCase ) def A ( self : Union[str, Any] , UpperCAmelCase : int ): lowerCAmelCase_ : Any = Node() lowerCAmelCase_ : int = current_node lowerCAmelCase_ : str = current_node lowerCAmelCase_ : Union[str, Any] = current_node for _ in range(1 , UpperCAmelCase ): lowerCAmelCase_ : Any = Node() lowerCAmelCase_ : Dict = current_node lowerCAmelCase_ : Optional[int] = previous_node lowerCAmelCase_ : Optional[Any] = current_node lowerCAmelCase_ : List[str] = self.front lowerCAmelCase_ : Optional[int] = previous_node def A ( self : Any ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A ( self : List[str] ): self.check_can_perform_operation() return self.front.data if self.front else None def A ( self : Optional[int] , UpperCAmelCase : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): lowerCAmelCase_ : int = self.rear.next if self.rear: lowerCAmelCase_ : Union[str, Any] = data def A ( self : List[Any] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: lowerCAmelCase_ : int = self.front.data lowerCAmelCase_ : Optional[Any] = None return data lowerCAmelCase_ : Optional[int] = self.front lowerCAmelCase_ : Any = old_front.next lowerCAmelCase_ : Tuple = old_front.data lowerCAmelCase_ : str = None return data def A ( self : Tuple ): if self.is_empty(): raise Exception("""Empty Queue""" ) def A ( self : List[str] ): if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class __a : def __init__( self : Any ): lowerCAmelCase_ : Any | None = None lowerCAmelCase_ : Node | None = None lowerCAmelCase_ : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
28
0
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def __magic_name__ ( __UpperCAmelCase ) -> 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(__UpperCAmelCase ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __magic_name__ ( ) -> Iterator[int]: '''simple docstring''' snake_case_ = 2 while True: if is_prime(__UpperCAmelCase ): yield num num += 1 def __magic_name__ ( __UpperCAmelCase = 200_0000 ) -> int: '''simple docstring''' return sum(takewhile(lambda __UpperCAmelCase : x < n, prime_generator() ) ) if __name__ == "__main__": print(f'''{solution() = }''')
56
"""simple docstring""" from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
77
0
import os import re 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 UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = {'vocab_file': 'spiece.model'} UpperCAmelCase_ = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCAmelCase_ = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class lowercase__ ( __lowerCamelCase ): '''simple docstring''' a : Any = VOCAB_FILES_NAMES a : Any = PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Dict = ["input_ids", "attention_mask"] a : List[int] = [] def __init__( self, __magic_name__, __magic_name__="<unk>", __magic_name__="<s>", __magic_name__="</s>", __magic_name__="<pad>", __magic_name__="[SEP]", __magic_name__="[MASK]", __magic_name__="[CLS]", __magic_name__ = None, **__magic_name__, ) -> None: """simple docstring""" UpperCamelCase__ : Dict = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else bos_token UpperCamelCase__ : Optional[int] = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else eos_token UpperCamelCase__ : Dict = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else unk_token UpperCamelCase__ : Optional[Any] = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else pad_token UpperCamelCase__ : Union[str, Any] = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else cls_token UpperCamelCase__ : List[Any] = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase__ : Any = AddedToken(__magic_name__, lstrip=__magic_name__, rstrip=__magic_name__ ) if isinstance(__magic_name__, __magic_name__ ) else mask_token UpperCamelCase__ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__magic_name__, eos_token=__magic_name__, unk_token=__magic_name__, pad_token=__magic_name__, sep_token=__magic_name__, mask_token=__magic_name__, cls_token=__magic_name__, sp_model_kwargs=self.sp_model_kwargs, **__magic_name__, ) UpperCamelCase__ : Any = vocab_file UpperCamelCase__ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) @property def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" return self.sp_model.get_piece_size() def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase__ : List[str] = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : Optional[int] = self.__dict__.copy() UpperCamelCase__ : int = None return state def __setstate__( self, __magic_name__ ) -> Optional[int]: """simple docstring""" UpperCamelCase__ : Tuple = d # for backward compatibility if not hasattr(self, '''sp_model_kwargs''' ): UpperCamelCase__ : List[Any] = {} UpperCamelCase__ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ ( self, __magic_name__ ) -> List[str]: """simple docstring""" return self.sp_model.encode(__magic_name__, out_type=__magic_name__ ) def UpperCamelCase__ ( self, __magic_name__ ) -> List[str]: """simple docstring""" return self.sp_model.piece_to_id(__magic_name__ ) def UpperCamelCase__ ( self, __magic_name__ ) -> str: """simple docstring""" UpperCamelCase__ : Tuple = self.sp_model.IdToPiece(__magic_name__ ) return token def UpperCamelCase__ ( self, __magic_name__ ) -> Any: """simple docstring""" UpperCamelCase__ : List[str] = [] UpperCamelCase__ : Dict = '''''' UpperCamelCase__ : Union[str, Any] = 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(__magic_name__ ) + token UpperCamelCase__ : str = True UpperCamelCase__ : Union[str, Any] = [] else: current_sub_tokens.append(__magic_name__ ) UpperCamelCase__ : Optional[Any] = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = False, __magic_name__ = None, __magic_name__ = True, **__magic_name__, ) -> str: """simple docstring""" UpperCamelCase__ : Optional[int] = kwargs.pop('''use_source_tokenizer''', __magic_name__ ) UpperCamelCase__ : str = self.convert_ids_to_tokens(__magic_name__, skip_special_tokens=__magic_name__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCamelCase__ : Optional[int] = [] UpperCamelCase__ : List[str] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__magic_name__ ) ) UpperCamelCase__ : Tuple = [] sub_texts.append(__magic_name__ ) else: current_sub_text.append(__magic_name__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__magic_name__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: UpperCamelCase__ : Any = re.sub(R''' (\[(MASK|SEP)\])''', R'''\1''', ''' '''.join(__magic_name__ ) ) else: UpperCamelCase__ : List[Any] = ''''''.join(__magic_name__ ) UpperCamelCase__ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCamelCase__ : Tuple = self.clean_up_tokenization(__magic_name__ ) return clean_text else: return text def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCamelCase__ : int = os.path.join( __magic_name__, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__, '''wb''' ) as fi: UpperCamelCase__ : List[str] = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase__ : Union[str, Any] = [self.cls_token_id] UpperCamelCase__ : int = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = None, __magic_name__ = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__, token_ids_a=__magic_name__, already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = None ) -> List[int]: """simple docstring""" UpperCamelCase__ : Optional[int] = [self.sep_token_id] UpperCamelCase__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
370
import qiskit def lowerCAmelCase_ ( __UpperCAmelCase: int , __UpperCAmelCase: int ) -> qiskit.result.counts.Counts: UpperCamelCase__ : Optional[Any] = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register UpperCamelCase__ : str = qiskit.QuantumCircuit(__UpperCAmelCase , __UpperCAmelCase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator UpperCamelCase__ : Union[str, Any] = qiskit.execute(__UpperCAmelCase , __UpperCAmelCase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__UpperCAmelCase ) if __name__ == "__main__": UpperCAmelCase_ = single_qubit_measure(2, 2) print(F'''Total count for various states are: {counts}''')
247
0
'''simple docstring''' import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : int=13 , lowerCAmelCase__ : Tuple=7 , lowerCAmelCase__ : int=True , lowerCAmelCase__ : int=True , lowerCAmelCase__ : Tuple=True , lowerCAmelCase__ : Union[str, Any]=True , lowerCAmelCase__ : Union[str, Any]=99 , lowerCAmelCase__ : Dict=32 , lowerCAmelCase__ : str=5 , lowerCAmelCase__ : int=4 , lowerCAmelCase__ : List[str]=37 , lowerCAmelCase__ : Any="gelu" , lowerCAmelCase__ : Any=0.1 , lowerCAmelCase__ : Union[str, Any]=0.1 , lowerCAmelCase__ : Tuple=512 , lowerCAmelCase__ : Optional[Any]=16 , lowerCAmelCase__ : List[str]=2 , lowerCAmelCase__ : Dict=0.02 , lowerCAmelCase__ : Any=4 , ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_attention_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_choices def snake_case__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_attention_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def snake_case__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def snake_case__ ( self : Tuple ) -> List[str]: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = True _UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" _snake_case : Tuple = True _snake_case : Optional[int] = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def snake_case__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = FlaxRobertaPreLayerNormModelTester(self ) @slow def snake_case__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' for model_class_name in self.all_model_classes: _UpperCamelCase = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowerCAmelCase__ ) _UpperCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @slow def snake_case__ ( self : Optional[int] ) -> Any: '''simple docstring''' _UpperCamelCase = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowerCAmelCase__ ) _UpperCamelCase = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] , dtype=jnp.intaa ) _UpperCamelCase = model(lowerCAmelCase__ )[0] _UpperCamelCase = [1, 11, 50265] self.assertEqual(list(output.shape ) , lowerCAmelCase__ ) # compare the actual values for a slice. _UpperCamelCase = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCAmelCase__ , atol=1e-4 ) ) @slow def snake_case__ ( self : Any ) -> List[str]: '''simple docstring''' _UpperCamelCase = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=lowerCAmelCase__ ) _UpperCamelCase = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] , dtype=jnp.intaa ) _UpperCamelCase = model(lowerCAmelCase__ )[0] # compare the actual values for a slice. _UpperCamelCase = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCAmelCase__ , atol=1e-4 ) )
324
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: lowercase__ : str = None lowercase__ : Optional[int] = logging.get_logger(__name__) lowercase__ : Optional[Any] = {'vocab_file': 'sentencepiece.model', 'tokenizer_file': 'tokenizer.json'} lowercase__ : int = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, 'tokenizer_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/tokenizer.json', }, } lowercase__ : Optional[int] = { 'google/rembert': 2_56, } lowercase__ : str = '▁' class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" _snake_case : str = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : Dict = RemBertTokenizer def __init__( self : List[Any] , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : str=True , lowerCAmelCase__ : Union[str, Any]=False , lowerCAmelCase__ : List[Any]="[CLS]" , lowerCAmelCase__ : str="[SEP]" , lowerCAmelCase__ : Optional[Any]="<unk>" , lowerCAmelCase__ : Optional[int]="[SEP]" , lowerCAmelCase__ : List[str]="<pad>" , lowerCAmelCase__ : str="[CLS]" , lowerCAmelCase__ : List[Any]="[MASK]" , **lowerCAmelCase__ : List[Any] , ) -> Any: '''simple docstring''' _UpperCamelCase = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , 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__ , **lowerCAmelCase__ , ) _UpperCamelCase = do_lower_case _UpperCamelCase = remove_space _UpperCamelCase = keep_accents _UpperCamelCase = vocab_file _UpperCamelCase = False if not self.vocab_file else True def snake_case__ ( self : Union[str, Any] , 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 cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def snake_case__ ( self : int , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None , lowerCAmelCase__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(lowerCAmelCase__ )) + [1] + ([0] * len(lowerCAmelCase__ )) + [1] return [1] + ([0] * len(lowerCAmelCase__ )) + [1] def snake_case__ ( self : List[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 ) * [0] + len(token_ids_a + sep ) * [1] def snake_case__ ( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCAmelCase__ ): logger.error('''Vocabulary path ({}) should be a directory'''.format(lowerCAmelCase__ ) ) return _UpperCamelCase = 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__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
324
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _a ( unittest.TestCase ): def snake_case ( self : Tuple ) -> Dict: '''simple docstring''' _UpperCamelCase : int = tempfile.mkdtemp() _UpperCamelCase : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file, '''w''', encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase : Dict = { '''do_resize''': True, '''size''': {'''height''': 2_2_4, '''width''': 2_2_4}, '''do_center_crop''': True, '''crop_size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073], '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711], '''do_convert_rgb''': True, } _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname, lowerCAmelCase__ ) with open(self.image_processor_file, '''w''', encoding='''utf-8''' ) as fp: json.dump(lowerCAmelCase__, lowerCAmelCase__ ) def snake_case ( self : str, **lowerCAmelCase__ : List[Any] ) -> Optional[int]: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : Union[str, Any], **lowerCAmelCase__ : Tuple ) -> str: '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : Any, **lowerCAmelCase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : str ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def snake_case ( self : Any ) -> int: '''simple docstring''' _UpperCamelCase : List[str] = [np.random.randint(2_5_5, size=(3, 3_0, 4_0_0), dtype=np.uinta )] _UpperCamelCase : List[Any] = [Image.fromarray(np.moveaxis(lowerCAmelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self : str ) -> Any: '''simple docstring''' _UpperCamelCase : Any = self.get_tokenizer() _UpperCamelCase : int = self.get_rust_tokenizer() _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCAmelCase__ ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer, lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer, lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor, lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor, lowerCAmelCase__ ) def snake_case ( self : int ) -> Tuple: '''simple docstring''' _UpperCamelCase : List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase : Dict = self.get_tokenizer(cls_token='''(CLS)''', sep_token='''(SEP)''' ) _UpperCamelCase : List[str] = self.get_image_processor(do_normalize=lowerCAmelCase__ ) _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname, cls_token='''(CLS)''', sep_token='''(SEP)''', do_normalize=lowerCAmelCase__ ) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer, lowerCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, lowerCAmelCase__ ) def snake_case ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase : List[str] = self.get_image_processor() _UpperCamelCase : str = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : List[str] = self.prepare_image_inputs() _UpperCamelCase : Any = image_processor(lowerCAmelCase__, return_tensors='''np''' ) _UpperCamelCase : Any = processor(images=lowerCAmelCase__, return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2 ) def snake_case ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase : Tuple = self.get_image_processor() _UpperCamelCase : Optional[Any] = self.get_tokenizer() _UpperCamelCase : Any = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Tuple = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : List[str] = processor(text=lowerCAmelCase__ ) _UpperCamelCase : Any = tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key] ) def snake_case ( self : Dict ) -> Tuple: '''simple docstring''' _UpperCamelCase : Tuple = self.get_image_processor() _UpperCamelCase : Optional[Any] = self.get_tokenizer() _UpperCamelCase : Dict = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Any = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : Union[str, Any] = self.prepare_image_inputs() _UpperCamelCase : str = processor(text=lowerCAmelCase__, images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ), ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def snake_case ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : int = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase : List[Any] = processor.batch_decode(lowerCAmelCase__ ) _UpperCamelCase : Dict = tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__, lowerCAmelCase__ ) def snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' _UpperCamelCase : Any = self.get_image_processor() _UpperCamelCase : Optional[int] = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Any = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : int = self.prepare_image_inputs() _UpperCamelCase : Dict = processor(text=lowerCAmelCase__, images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ), processor.model_input_names )
128
"""simple docstring""" import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase_ =get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp UpperCamelCase_ =5 UpperCamelCase_ =10 @require_sentencepiece @require_tokenizers class _a ( _lowerCAmelCase , unittest.TestCase ): UpperCamelCase = SpeechaTextTokenizer UpperCamelCase = False UpperCamelCase = True def snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' super().setUp() _UpperCamelCase : Dict = sp.SentencePieceProcessor() spm_model.Load(lowerCAmelCase__ ) _UpperCamelCase : Union[str, Any] = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(lowerCAmelCase__ ) )] _UpperCamelCase : Tuple = dict(zip(lowerCAmelCase__, range(len(lowerCAmelCase__ ) ) ) ) _UpperCamelCase : Dict = Path(self.tmpdirname ) save_json(lowerCAmelCase__, save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(lowerCAmelCase__, save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) _UpperCamelCase : List[str] = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self : str ) -> str: '''simple docstring''' _UpperCamelCase : List[str] = '''<pad>''' _UpperCamelCase : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ), lowerCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ), lowerCAmelCase__ ) def snake_case ( self : Any ) -> Optional[int]: '''simple docstring''' _UpperCamelCase : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<s>''' ) self.assertEqual(vocab_keys[1], '''<pad>''' ) self.assertEqual(vocab_keys[-1], '''j''' ) self.assertEqual(len(lowerCAmelCase__ ), 1_0_0_1 ) def snake_case ( self : Any ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 1_0_0_1 ) def snake_case ( self : List[Any] ) -> Tuple: '''simple docstring''' _UpperCamelCase : Optional[int] = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) _UpperCamelCase : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase__, ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ), [2_8_9, 5_0, 1_4, 1_7_4, 3_8_6], ) _UpperCamelCase : List[str] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase__, [SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.'''], ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__, [1_2, 2_5, 8_8, 5_9, 2_8, 2_3, 1_1, 4, 6_0_6, 3_5_1, 3_5_1, 3_5_1, 7, 1_6, 7_0, 5_0, 7_6, 8_4, 1_0, 4, 8] ) _UpperCamelCase : Union[str, Any] = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__, [SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.'''], ) @slow def snake_case ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : Any = {'''input_ids''': [[3_7_9_1, 7_9_7, 3_1, 1_1, 6_4, 7_9_7, 3_1, 2_4_2_9, 4_3_3, 1_2, 1_1_7_6, 1_2, 2_0, 7_8_6, 9_1_5, 1_4_2, 2_4_1_3, 2_4_0, 3_7, 3_2_3_8, 7_9_7, 3_1, 1_1, 3_5, 9_3, 9_1_5, 1_4_2, 2_4_1_3, 2_4_0, 3_7, 5_5_4_0, 5_6_7, 1_2_7_6, 9_3, 3_7, 6_1_0, 4_0, 6_2, 4_5_5, 6_5_7, 1_0_4_2, 1_2_3, 7_8_0, 1_7_7, 3_7, 3_0_9, 2_4_1, 1_2_9_8, 5_1_4, 2_0, 2_9_2, 2_7_3_7, 1_1_4, 2_4_6_9, 2_4_1, 8_5, 6_4, 3_0_2, 5_4_8, 5_2_8, 4_2_3, 4, 5_0_9, 4_0_6, 4_2_3, 3_7, 6_0_1, 4, 7_7_7, 3_0_2, 5_4_8, 5_2_8, 4_2_3, 2_8_4, 4, 3_3_8_8, 5_1_1, 4_5_9, 4, 3_5_5_5, 4_0, 3_2_1, 3_0_2, 7_0_5, 4, 3_3_8_8, 5_1_1, 5_8_3, 3_2_6, 5, 5, 5, 6_2, 3_3_1_0, 5_6_0, 1_7_7, 2_6_8_0, 2_1_7, 1_5_0_8, 3_2, 3_1, 8_5_3, 4_1_8, 6_4, 5_8_3, 5_1_1, 1_6_0_5, 6_2, 3_5, 9_3, 5_6_0, 1_7_7, 2_6_8_0, 2_1_7, 1_5_0_8, 1_5_2_1, 6_4, 5_8_3, 5_1_1, 5_1_9, 6_2, 2_0, 1_5_1_5, 7_6_4, 2_0, 1_4_9, 2_6_1, 5_6_2_5, 7_9_7_2, 2_0, 5_5_4_0, 5_6_7, 1_2_7_6, 9_3, 3_9_2_5, 1_6_7_5, 1_1, 1_5, 8_0_2, 7_9_7_2, 5_7_6, 2_1_7, 1_5_0_8, 1_1, 3_5, 9_3, 1_2_5_3, 2_4_4_1, 1_5, 2_8_9, 6_5_2, 3_1, 4_1_6, 3_2_1, 3_8_4_2, 1_1_5, 4_0, 9_1_1, 8, 4_7_6, 6_1_9, 4, 3_8_0, 1_4_2, 4_2_3, 3_3_5, 2_4_0, 3_5, 9_3, 2_6_4, 8, 1_1, 3_3_5, 5_6_9, 4_2_0, 1_6_3, 5, 2], [2_6_0, 5_4_8, 5_2_8, 4_2_3, 2_0, 4_5_1, 2_0, 2_6_8_1, 1_1_5_3, 3_4_3_4, 2_0, 5_5_4_0, 3_7, 5_6_7, 1_2_6, 1_2_5_3, 2_4_4_1, 3_3_7_6, 4_4_9, 2_1_0, 4_3_1, 1_5_6_3, 1_7_7, 7_6_7, 5_5_4_0, 1_1, 1_2_0_3, 4_7_2, 1_1, 2_9_5_3, 6_8_5, 2_8_5, 3_6_4, 7_0_6, 1_1_5_3, 2_0, 6_7_9_9, 2_0, 2_8_6_9, 2_0, 4_4_6_4, 1_2_6, 4_0, 2_4_2_9, 2_0, 1_0_4_0, 8_6_6, 2_6_6_4, 4_1_8, 2_0, 3_1_8, 2_0, 1_7_2_6, 1_8_6, 2_0, 2_6_5, 5_2_2, 3_5, 9_3, 2_1_9_1, 4_6_3_4, 2_0, 1_0_4_0, 1_2, 6_7_9_9, 1_5, 2_2_8, 2_3_5_6, 1_4_2, 3_1, 1_1, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_5_7_5, 2_6_6_6, 6_8_4, 1_5_8_2, 1_1_7_6, 1_2, 6_2_7, 1_4_9, 6_1_9, 2_0, 4_9_0_2, 5_6_3, 1_1, 2_0, 1_4_9, 2_6_1, 3_4_2_0, 2_3_5_6, 1_7_4, 1_4_2, 4_7_1_4, 1_3_1, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase__, model_name='''facebook/s2t-small-mustc-en-de-st''', revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''', ) @require_sentencepiece class _a ( unittest.TestCase ): UpperCamelCase = '''valhalla/s2t_mustc_multilinguial_medium''' UpperCamelCase = '''C\'est trop cool''' UpperCamelCase = '''Esto es genial''' @classmethod def snake_case ( cls : Dict ) -> str: '''simple docstring''' _UpperCamelCase : SpeechaTextTokenizer = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def snake_case ( self : Tuple ) -> List[str]: '''simple docstring''' self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''], 4 ) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''], 6 ) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''], 9 ) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''], 1_1 ) def snake_case ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' self.assertEqual(self.tokenizer.vocab_size, 1_0_0_0_0 ) def snake_case ( self : Any ) -> Union[str, Any]: '''simple docstring''' self.assertIn(lowerCAmelCase__, self.tokenizer.all_special_ids ) _UpperCamelCase : List[Any] = [ES_CODE, 4, 1_6_0_1, 4_7, 7_6_4_7, 2] _UpperCamelCase : Optional[Any] = self.tokenizer.decode(lowerCAmelCase__, skip_special_tokens=lowerCAmelCase__ ) _UpperCamelCase : Optional[int] = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=lowerCAmelCase__ ) self.assertEqual(lowerCAmelCase__, lowerCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token, lowerCAmelCase__ ) def snake_case ( self : List[str] ) -> List[str]: '''simple docstring''' _UpperCamelCase : Dict = '''fr''' _UpperCamelCase : int = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0], lowerCAmelCase__ ) self.assertEqual(encoded[-1], self.tokenizer.eos_token_id ) def snake_case ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : Dict = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens, [FR_CODE] ) _UpperCamelCase : List[str] = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens, [ES_CODE] )
128
1
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' if not head: return True # split the list to two parts _UpperCAmelCase , _UpperCAmelCase = head.next, head while fast and fast.next: _UpperCAmelCase = fast.next.next _UpperCAmelCase = slow.next _UpperCAmelCase = slow.next _UpperCAmelCase = None # Don't forget here! But forget still works! # reverse the second part _UpperCAmelCase = None while second: _UpperCAmelCase = second.next _UpperCAmelCase = node _UpperCAmelCase = second _UpperCAmelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False _UpperCAmelCase = node.next _UpperCAmelCase = head.next return True def lowercase ( _SCREAMING_SNAKE_CASE : Optional[int] ): '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) _UpperCAmelCase = _UpperCAmelCase = _UpperCAmelCase = head while fast and fast.next: _UpperCAmelCase , _UpperCAmelCase = fast.next.next, slow.next # 2. Push the second half into the stack _UpperCAmelCase = [slow.val] while slow.next: _UpperCAmelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False _UpperCAmelCase = cur.next return True def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if not head or not head.next: return True _UpperCAmelCase = {} _UpperCAmelCase = 0 while head: if head.val in d: d[head.val].append(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = [pos] _UpperCAmelCase = head.next pos += 1 _UpperCAmelCase = pos - 1 _UpperCAmelCase = 0 for v in d.values(): if len(_SCREAMING_SNAKE_CASE ) % 2 != 0: middle += 1 else: _UpperCAmelCase = 0 for i in range(0 , len(_SCREAMING_SNAKE_CASE ) ): if v[i] + v[len(_SCREAMING_SNAKE_CASE ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
260
"""simple docstring""" def lowercase ( _SCREAMING_SNAKE_CASE : list ): '''simple docstring''' if len(_SCREAMING_SNAKE_CASE ) <= 1: return lst _UpperCAmelCase = 1 while i < len(_SCREAMING_SNAKE_CASE ): if lst[i - 1] <= lst[i]: i += 1 else: _UpperCAmelCase , _UpperCAmelCase = lst[i], lst[i - 1] i -= 1 if i == 0: _UpperCAmelCase = 1 return lst if __name__ == "__main__": __A : Dict = input("Enter numbers separated by a comma:\n").strip() __A : List[Any] = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
260
1
"""simple docstring""" _lowercase : int = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _lowercase : int = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _lowercase : Any = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def lowercase__ ( snake_case_ :int , snake_case_ :int , snake_case_ :int ): assert len(str(snake_case_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __UpperCAmelCase = year // 100 __UpperCAmelCase = (5 * (century % 4) + 2) % 7 __UpperCAmelCase = year % 100 __UpperCAmelCase = centurian % 12 __UpperCAmelCase = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __UpperCAmelCase = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __UpperCAmelCase = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
86
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
86
1
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Optional[int] =hf_hub_url(repo_id=__a , path=__a , revision=__a ) assert url == F"""https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(__a )}"""
10
"""simple docstring""" from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def lowercase_ ( _snake_case ,_snake_case ,_snake_case = None ): SCREAMING_SNAKE_CASE__ : Dict = tesseract_config if tesseract_config is not None else """""" # apply OCR SCREAMING_SNAKE_CASE__ : List[Any] = to_pil_image(_snake_case ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = pil_image.size SCREAMING_SNAKE_CASE__ : Tuple = pytesseract.image_to_data(_snake_case ,lang=_snake_case ,output_type="""dict""" ,config=_snake_case ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE__ : Union[str, Any] = [idx for idx, word in enumerate(_snake_case ) if not word.strip()] SCREAMING_SNAKE_CASE__ : Dict = [word for idx, word in enumerate(_snake_case ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : List[str] = [coord for idx, coord in enumerate(_snake_case ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : Tuple = [coord for idx, coord in enumerate(_snake_case ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : int = [coord for idx, coord in enumerate(_snake_case ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : Tuple = [coord for idx, coord in enumerate(_snake_case ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE__ : List[Any] = [] for x, y, w, h in zip(_snake_case ,_snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [x, y, x + w, y + h] actual_boxes.append(_snake_case ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE__ : List[str] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(_snake_case ,_snake_case ,_snake_case ) ) assert len(_snake_case ) == len(_snake_case ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : Optional[int] = ['''pixel_values'''] def __init__(self , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "" , **SCREAMING_SNAKE_CASE__ , ) -> None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = size if size is not None else {"""height""": 2_24, """width""": 2_24} SCREAMING_SNAKE_CASE__ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize SCREAMING_SNAKE_CASE__ : Any = size SCREAMING_SNAKE_CASE__ : List[Any] = resample SCREAMING_SNAKE_CASE__ : Dict = apply_ocr SCREAMING_SNAKE_CASE__ : List[str] = ocr_lang SCREAMING_SNAKE_CASE__ : Tuple = tesseract_config def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : Any = (size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Optional[Any] = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE__ : Optional[Any] = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE__ : Dict = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE__ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Dict = [] for image in images: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = apply_tesseract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) words_batch.append(SCREAMING_SNAKE_CASE__ ) boxes_batch.append(SCREAMING_SNAKE_CASE__ ) if do_resize: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [flip_channel_order(SCREAMING_SNAKE_CASE__ ) for image in images] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE__ ) if apply_ocr: SCREAMING_SNAKE_CASE__ : List[Any] = words_batch SCREAMING_SNAKE_CASE__ : List[str] = boxes_batch return data
25
0
"""simple docstring""" 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''' __UpperCamelCase = PegasusConfig __UpperCamelCase = {} __UpperCamelCase = "gelu" def __init__( self : Optional[int] , lowercase_ : Tuple , lowercase_ : Optional[Any]=13 , lowercase_ : Optional[int]=7 , lowercase_ : Optional[int]=True , lowercase_ : Any=False , lowercase_ : Tuple=99 , lowercase_ : int=32 , lowercase_ : Optional[Any]=2 , lowercase_ : int=4 , lowercase_ : int=37 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : str=0.1 , lowercase_ : List[Any]=40 , lowercase_ : Optional[int]=2 , lowercase_ : List[Any]=1 , lowercase_ : Dict=0 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : Dict = batch_size SCREAMING_SNAKE_CASE_ : List[Any] = seq_length SCREAMING_SNAKE_CASE_ : Optional[Any] = is_training SCREAMING_SNAKE_CASE_ : List[Any] = use_labels SCREAMING_SNAKE_CASE_ : Any = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : int = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token_id SCREAMING_SNAKE_CASE_ : int = pad_token_id SCREAMING_SNAKE_CASE_ : List[str] = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.concat([input_ids, eos_tensor] , axis=1) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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 , ) SCREAMING_SNAKE_CASE_ : List[str] = prepare_pegasus_inputs_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_) return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Tuple , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = TFPegasusModel(config=SCREAMING_SNAKE_CASE_).get_decoder() SCREAMING_SNAKE_CASE_ : List[Any] = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE_ : int = inputs_dict["""attention_mask"""][:1, :] SCREAMING_SNAKE_CASE_ : List[Any] = inputs_dict["""head_mask"""] SCREAMING_SNAKE_CASE_ : Dict = 1 # first forward pass SCREAMING_SNAKE_CASE_ : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_) SCREAMING_SNAKE_CASE_ : Tuple = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE_ : List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2) , tf.inta) # append to next input_ids and SCREAMING_SNAKE_CASE_ : Dict = tf.concat([input_ids, next_tokens] , axis=-1) SCREAMING_SNAKE_CASE_ : Any = tf.concat([attention_mask, next_attn_mask] , axis=-1) SCREAMING_SNAKE_CASE_ : str = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_)[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_)[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1]) # select random slice SCREAMING_SNAKE_CASE_ : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1])) SCREAMING_SNAKE_CASE_ : Tuple = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE_ : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , rtol=1e-3) def _A (__a , __a , __a , __a=None , __a=None , __a=None , __a=None , __a=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE_ : Dict = tf.cast(tf.math.not_equal(lowerCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE_ : Any = 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: SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE_ : Tuple = 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__ ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = TFPegasusModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE_) @require_sentencepiece @require_tokenizers @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = [ " 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!\" ", ] __UpperCamelCase = [ "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 __UpperCamelCase = "google/pegasus-xsum" @cached_property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return AutoTokenizer.from_pretrained(self.model_name) @cached_property def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name) return model def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.translate_src_text(**SCREAMING_SNAKE_CASE_) assert self.expected_text == generated_words def _SCREAMING_SNAKE_CASE ( self : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer(self.src_text , **SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='''tf''') SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ : Any = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=SCREAMING_SNAKE_CASE_) return generated_words @slow def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self._assert_generated_batch_equal_expected()
366
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" 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()
318
0
"""simple docstring""" from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP __magic_name__ = logging.get_logger(__name__) # pylint: disable=invalid-name __magic_name__ = "\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"red cat, 4k photo\"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")\n >>> pipe.to(\"cuda\")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save(\"cat.png\")\n ```\n" def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=8 ): __SCREAMING_SNAKE_CASE = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __SCREAMING_SNAKE_CASE = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ): super().__init__() self.register_modules( text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , movq=lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels) - 1) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): if latents is None: __SCREAMING_SNAKE_CASE = randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ , dtype=lowerCAmelCase__) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") __SCREAMING_SNAKE_CASE = latents.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , ): __SCREAMING_SNAKE_CASE = len(lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else 1 # get prompt text embeddings __SCREAMING_SNAKE_CASE = self.tokenizer( lowerCAmelCase__ , padding="""max_length""" , truncation=lowerCAmelCase__ , max_length=7_7 , return_attention_mask=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = text_inputs.input_ids __SCREAMING_SNAKE_CASE = self.tokenizer(lowerCAmelCase__ , padding="""longest""" , return_tensors="""pt""").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f" {self.tokenizer.model_max_length} tokens: {removed_text}") __SCREAMING_SNAKE_CASE = text_input_ids.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = text_inputs.attention_mask.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self.text_encoder( input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = prompt_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = text_encoder_hidden_states.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = text_mask.repeat_interleave(lowerCAmelCase__ , dim=0) if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE = 42 if negative_prompt is None: __SCREAMING_SNAKE_CASE = [""""""] * batch_size elif type(lowerCAmelCase__) is not type(lowerCAmelCase__): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(lowerCAmelCase__)} !=" f" {type(lowerCAmelCase__)}.") elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [negative_prompt] elif batch_size != len(lowerCAmelCase__): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(lowerCAmelCase__)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""") else: __SCREAMING_SNAKE_CASE = negative_prompt __SCREAMING_SNAKE_CASE = self.tokenizer( lowerCAmelCase__ , padding="""max_length""" , max_length=7_7 , truncation=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = uncond_input.input_ids.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = uncond_input.attention_mask.to(lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self.text_encoder( input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE = negative_prompt_embeds.shape[1] __SCREAMING_SNAKE_CASE = negative_prompt_embeds.repeat(1 , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.shape[1] __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.repeat(1 , lowerCAmelCase__ , 1) __SCREAMING_SNAKE_CASE = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , lowerCAmelCase__ , -1) __SCREAMING_SNAKE_CASE = uncond_text_mask.repeat_interleave(lowerCAmelCase__ , dim=0) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __SCREAMING_SNAKE_CASE = torch.cat([negative_prompt_embeds, prompt_embeds]) __SCREAMING_SNAKE_CASE = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]) __SCREAMING_SNAKE_CASE = torch.cat([uncond_text_mask, text_mask]) return prompt_embeds, text_encoder_hidden_states, text_mask def snake_case_ ( self , lowerCAmelCase__=0): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""") __SCREAMING_SNAKE_CASE = torch.device(f"cuda:{gpu_id}") __SCREAMING_SNAKE_CASE = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCAmelCase__ , lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__=0): if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0"""): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""") __SCREAMING_SNAKE_CASE = torch.device(f"cuda:{gpu_id}") if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCAmelCase__) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cpu_offload_with_hook(lowerCAmelCase__ , lowerCAmelCase__ , prev_module_hook=lowerCAmelCase__) if self.safety_checker is not None: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cpu_offload_with_hook(self.safety_checker , lowerCAmelCase__ , prev_module_hook=lowerCAmelCase__) # We'll offload the last model manually. __SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_ ( self): if not hasattr(self.unet , """_hf_hook"""): return self.device for module in self.unet.modules(): if ( hasattr(lowerCAmelCase__ , """_hf_hook""") and hasattr(module._hf_hook , """execution_device""") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device @torch.no_grad() @replace_example_docstring(lowerCAmelCase__) def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = 5_1_2 , lowerCAmelCase__ = 5_1_2 , lowerCAmelCase__ = 1_0_0 , lowerCAmelCase__ = 4.0 , lowerCAmelCase__ = 1 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = "pil" , lowerCAmelCase__ = True , ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = 1 elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = len(lowerCAmelCase__) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__)}") __SCREAMING_SNAKE_CASE = self._execution_device __SCREAMING_SNAKE_CASE = batch_size * num_images_per_prompt __SCREAMING_SNAKE_CASE = guidance_scale > 1.0 __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self._encode_prompt( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = torch.cat(lowerCAmelCase__ , dim=0) if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = torch.cat(lowerCAmelCase__ , dim=0) if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(lowerCAmelCase__ , dim=0) __SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0).to( dtype=prompt_embeds.dtype , device=lowerCAmelCase__) self.scheduler.set_timesteps(lowerCAmelCase__ , device=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = self.scheduler.timesteps __SCREAMING_SNAKE_CASE = self.unet.config.in_channels __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = get_new_h_w(lowerCAmelCase__ , lowerCAmelCase__ , self.movq_scale_factor) # create initial latent __SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCAmelCase__)): # expand the latents if we are doing classifier free guidance __SCREAMING_SNAKE_CASE = torch.cat([latents] * 2) if do_classifier_free_guidance else latents __SCREAMING_SNAKE_CASE = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} __SCREAMING_SNAKE_CASE = self.unet( sample=lowerCAmelCase__ , timestep=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , added_cond_kwargs=lowerCAmelCase__ , return_dict=lowerCAmelCase__ , )[0] if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.chunk(2) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = variance_pred.chunk(2) __SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , """variance_type""") and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE = self.scheduler.step( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , generator=lowerCAmelCase__ , ).prev_sample # post-processing __SCREAMING_SNAKE_CASE = self.movq.decode(lowerCAmelCase__ , force_not_quantize=lowerCAmelCase__)["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}") if output_type in ["np", "pil"]: __SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE = image.clamp(0 , 1) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(lowerCAmelCase__) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase__)
100
'''simple docstring''' import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''0.12.2'''): raise Exception('''requires fairseq >= 0.12.2''') if version.parse(fairseq.__version__) > version.parse('''2'''): raise Exception('''requires fairseq < v2''') logging.set_verbosity_info() __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : List[str] = '''Hello, World!''' __lowercase : Union[str, Any] = '''en_XX''' def lowercase_ ( _lowercase , _lowercase , _lowercase ) -> Dict: '''simple docstring''' lowerCamelCase_ : Tuple = Path('''data_bin''' ) lowerCamelCase_ : Dict = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(_lowercase ).parent ) , checkpoint_file=Path(_lowercase ).name , _name='''xmod_base''' , arch='''xmod_base''' , task='''multilingual_masked_lm''' , data_name_or_path=str(_lowercase ) , bpe='''sentencepiece''' , sentencepiece_model=str(Path(_lowercase ).parent / '''sentencepiece.bpe.model''' ) , src_dict=str(data_dir / '''dict.txt''' ) , ) xmod.eval() # disable dropout print(_lowercase ) lowerCamelCase_ : Dict = xmod.model.encoder.sentence_encoder lowerCamelCase_ : List[Any] = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , '''bottleneck''' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: lowerCamelCase_ : Tuple = xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our X-MOD config:''' , _lowercase ) lowerCamelCase_ : int = XmodForSequenceClassification(_lowercase ) if classification_head else XmodForMaskedLM(_lowercase ) model.eval() # Now let's copy all the weights. # Embeddings lowerCamelCase_ : Dict = xmod_sent_encoder.embed_tokens.weight lowerCamelCase_ : str = xmod_sent_encoder.embed_positions.weight lowerCamelCase_ : Optional[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. lowerCamelCase_ : Union[str, Any] = xmod_sent_encoder.layernorm_embedding.weight lowerCamelCase_ : Dict = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowerCamelCase_ : List[str] = model.roberta.encoder.layer[i] lowerCamelCase_ : int = xmod_sent_encoder.layers[i] # self attention lowerCamelCase_ : Dict = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('''Dimensions of self-attention weights do not match.''' ) lowerCamelCase_ : List[Any] = xmod_layer.self_attn.q_proj.weight lowerCamelCase_ : Optional[int] = xmod_layer.self_attn.q_proj.bias lowerCamelCase_ : Any = xmod_layer.self_attn.k_proj.weight lowerCamelCase_ : Tuple = xmod_layer.self_attn.k_proj.bias lowerCamelCase_ : str = xmod_layer.self_attn.v_proj.weight lowerCamelCase_ : Optional[Any] = xmod_layer.self_attn.v_proj.bias # self-attention output lowerCamelCase_ : Optional[Any] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('''Dimensions of self-attention output weights do not match.''' ) lowerCamelCase_ : List[str] = xmod_layer.self_attn.out_proj.weight lowerCamelCase_ : int = xmod_layer.self_attn.out_proj.bias lowerCamelCase_ : Any = xmod_layer.self_attn_layer_norm.weight lowerCamelCase_ : Dict = xmod_layer.self_attn_layer_norm.bias # intermediate lowerCamelCase_ : str = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of intermediate weights do not match.''' ) lowerCamelCase_ : Tuple = xmod_layer.fca.weight lowerCamelCase_ : str = xmod_layer.fca.bias # output lowerCamelCase_ : Union[str, Any] = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of feed-forward weights do not match.''' ) lowerCamelCase_ : Optional[int] = xmod_layer.fca.weight lowerCamelCase_ : Optional[Any] = xmod_layer.fca.bias lowerCamelCase_ : Dict = xmod_layer.final_layer_norm.weight lowerCamelCase_ : Optional[Any] = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: lowerCamelCase_ : Optional[int] = xmod_layer.adapter_layer_norm.weight lowerCamelCase_ : Tuple = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('''Lists of language adapters do not match.''' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): lowerCamelCase_ : List[str] = bert_output.adapter_modules[lang_code] lowerCamelCase_ : Optional[Any] = xmod_layer.adapter_modules[lang_code] lowerCamelCase_ : List[Any] = from_adapter.fca.weight lowerCamelCase_ : str = from_adapter.fca.bias lowerCamelCase_ : Union[str, Any] = from_adapter.fca.weight lowerCamelCase_ : int = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: lowerCamelCase_ : str = xmod_sent_encoder.layer_norm.weight lowerCamelCase_ : Any = xmod_sent_encoder.layer_norm.bias if classification_head: lowerCamelCase_ : Optional[int] = xmod.model.classification_heads['''mnli'''].dense.weight lowerCamelCase_ : Union[str, Any] = xmod.model.classification_heads['''mnli'''].dense.bias lowerCamelCase_ : List[Any] = xmod.model.classification_heads['''mnli'''].out_proj.weight lowerCamelCase_ : str = xmod.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head lowerCamelCase_ : List[str] = xmod.model.encoder.lm_head.dense.weight lowerCamelCase_ : Optional[Any] = xmod.model.encoder.lm_head.dense.bias lowerCamelCase_ : Dict = xmod.model.encoder.lm_head.layer_norm.weight lowerCamelCase_ : Union[str, Any] = xmod.model.encoder.lm_head.layer_norm.bias lowerCamelCase_ : List[Any] = xmod.model.encoder.lm_head.weight lowerCamelCase_ : Any = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. lowerCamelCase_ : Dict = xmod.encode(_lowercase ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(_lowercase ) lowerCamelCase_ : Tuple = model(_lowercase )[0] if classification_head: lowerCamelCase_ : Union[str, Any] = xmod.model.classification_heads['''mnli'''](xmod.extract_features(_lowercase ) ) else: lowerCamelCase_ : Union[str, Any] = xmod.model(_lowercase , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) lowerCamelCase_ : Any = torch.max(torch.abs(our_output - their_output ) ).item() print(F"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 lowerCamelCase_ : Optional[int] = torch.allclose(_lowercase , _lowercase , atol=1e-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) Path(_lowercase ).mkdir(parents=_lowercase , exist_ok=_lowercase ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) if __name__ == "__main__": __lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) __lowercase : Any = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
318
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : str = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys UpperCAmelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
363
"""simple docstring""" from collections.abc import Sequence def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase = False ) -> float: '''simple docstring''' if not arr: return 0 lowercase_ = 0 if allow_empty_subarrays else float("""-inf""" ) lowercase_ = 0.0 for num in arr: lowercase_ = max(0 if allow_empty_subarrays else num , curr_sum + num ) lowercase_ = max(__lowerCAmelCase , __lowerCAmelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase : Union[str, Any] = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F"{max_subarray_sum(nums) = }")
313
0
"""simple docstring""" from string import ascii_lowercase, ascii_uppercase def lowercase_ ( _snake_case ): if not sentence: return "" SCREAMING_SNAKE_CASE__ : int = dict(zip(_snake_case ,_snake_case ) ) return lower_to_upper.get(sentence[0] ,sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
25
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''MMBTForClassification''', '''MMBTModel''', '''ModalEmbeddings'''] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
235
0
'''simple docstring''' import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = BertTokenizer A_ = BertTokenizerFast A_ = True A_ = True A_ = filter_non_english def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() __a : Union[str, Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = 'UNwant\u00E9d,running' __a : List[str] = 'unwanted, running' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.tokenizer_class(self.vocab_file ) __a : int = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : Union[str, Any] = self.get_tokenizer() __a : Dict = self.get_rust_tokenizer() __a : int = 'UNwant\u00E9d,running' __a : Tuple = tokenizer.tokenize(__a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Tuple = tokenizer.encode(__a , add_special_tokens=__a ) __a : str = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : Dict = self.get_rust_tokenizer() __a : int = tokenizer.encode(__a ) __a : Tuple = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # With lower casing __a : Optional[int] = self.get_tokenizer(do_lower_case=__a ) __a : Any = self.get_rust_tokenizer(do_lower_case=__a ) __a : List[str] = 'UNwant\u00E9d,running' __a : int = tokenizer.tokenize(__a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Any = tokenizer.encode(__a , add_special_tokens=__a ) __a : str = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : Dict = self.get_rust_tokenizer() __a : Optional[Any] = tokenizer.encode(__a ) __a : Optional[int] = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = BasicTokenizer() __a : Union[str, Any] = 'a\n\'ll !!to?\'d of, can\'t.' __a : Any = ['a', '\'', 'll', '!', '!', 'to', '?', '\'', 'd', 'of', ',', 'can', '\'', 't', '.'] self.assertListEqual(tokenizer.tokenize(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __a : str = {} for i, token in enumerate(__a ): __a : Union[str, Any] = i __a : Dict = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.tokenizer_class.from_pretrained('bert-base-uncased' ) __a : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __a : Tuple = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __a : Any = tokenizer.build_inputs_with_special_tokens(__a ) __a : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __UpperCAmelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : str = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : Dict = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __a : str = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) __a : Optional[int] = tokenizer_r.do_lower_case if hasattr(__a , 'do_lower_case' ) else False __a : int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ['的', '人', '有'] __a : Optional[Any] = ''.join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : List[Any] = True __a : Union[str, Any] = self.tokenizer_class.from_pretrained(__a , **__a ) __a : Tuple = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : Optional[int] = tokenizer_p.encode(__a , add_special_tokens=__a ) __a : str = tokenizer_r.encode(__a , add_special_tokens=__a ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(__a ) __a : Any = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) __a : Optional[int] = False __a : List[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : List[Any] = self.tokenizer_class.from_pretrained(__a , **__a ) __a : Tuple = tokenizer_r.encode(__a , add_special_tokens=__a ) __a : Union[str, Any] = tokenizer_p.encode(__a , add_special_tokens=__a ) __a : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) __a : str = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". __a : int = [ f"""##{token}""" if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a )
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __lowercase : str = logging.get_logger(__name__) # General docstring __lowercase : List[str] = 'MobileNetV1Config' # Base docstring __lowercase : Tuple = 'google/mobilenet_v1_1.0_224' __lowercase : List[Any] = [1, 10_24, 7, 7] # Image classification docstring __lowercase : int = 'google/mobilenet_v1_1.0_224' __lowercase : Any = 'tabby, tabby cat' __lowercase : Dict = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any]=None ): __a : Dict = {} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = model.mobilenet_va else: __a : List[Any] = model __a : Dict = 'MobilenetV1/Conv2d_0/' __a : Dict = backbone.conv_stem.convolution.weight __a : Optional[Any] = backbone.conv_stem.normalization.bias __a : int = backbone.conv_stem.normalization.weight __a : int = backbone.conv_stem.normalization.running_mean __a : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): __a : int = i + 1 __a : Dict = i * 2 __a : Dict = backbone.layer[pt_index] __a : Dict = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" __a : Union[str, Any] = pointer.convolution.weight __a : Optional[Any] = pointer.normalization.bias __a : Union[str, Any] = pointer.normalization.weight __a : List[Any] = pointer.normalization.running_mean __a : Tuple = pointer.normalization.running_var __a : List[str] = backbone.layer[pt_index + 1] __a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" __a : Optional[int] = pointer.convolution.weight __a : List[str] = pointer.normalization.bias __a : Dict = pointer.normalization.weight __a : Dict = pointer.normalization.running_mean __a : Optional[int] = pointer.normalization.running_var if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Any = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __a : Optional[int] = model.classifier.weight __a : List[Any] = model.classifier.bias return tf_to_pt_map def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __a : Union[str, Any] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) __a : List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = array # Build TF to PyTorch weights loading map __a : Optional[int] = _build_tf_to_pytorch_map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue __a : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __a : Optional[Any] = np.transpose(_SCREAMING_SNAKE_CASE , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __a : Union[str, Any] = array.squeeze().transpose() else: __a : Dict = np.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) __a : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) tf_weights.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp_1' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/ExponentialMovingAverage' , _SCREAMING_SNAKE_CASE ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def lowerCamelCase (_SCREAMING_SNAKE_CASE : torch.Tensor , _SCREAMING_SNAKE_CASE : nn.Convad ): __a , __a : Any = features.shape[-2:] __a , __a : int = conv_layer.stride __a , __a : Any = conv_layer.kernel_size if in_height % stride_height == 0: __a : int = max(kernel_height - stride_height , 0 ) else: __a : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __a : Any = max(kernel_width - stride_width , 0 ) else: __a : str = max(kernel_width - (in_width % stride_width) , 0 ) __a : int = pad_along_width // 2 __a : Dict = pad_along_width - pad_left __a : List[str] = pad_along_height // 2 __a : Union[str, Any] = pad_along_height - pad_top __a : str = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'constant' , 0.0 ) class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a , __a , __a , __a = 1 , __a = 1 , __a = False , __a = True , __a = True , ): '''simple docstring''' super().__init__() __a : Optional[int] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) __a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __a : Union[str, Any] = nn.Convad( in_channels=__a , out_channels=__a , kernel_size=__a , stride=__a , padding=__a , groups=__a , bias=__a , padding_mode='zeros' , ) if use_normalization: __a : List[str] = nn.BatchNormad( num_features=__a , eps=config.layer_norm_eps , momentum=0.9997 , affine=__a , track_running_stats=__a , ) else: __a : Tuple = None if use_activation: if isinstance(__a , __a ): __a : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , __a ): __a : Union[str, Any] = ACTaFN[config.hidden_act] else: __a : Dict = config.hidden_act else: __a : List[Any] = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.tf_padding: __a : Union[str, Any] = apply_tf_padding(__a , self.convolution ) __a : Union[str, Any] = self.convolution(__a ) if self.normalization is not None: __a : str = self.normalization(__a ) if self.activation is not None: __a : Optional[int] = self.activation(__a ) return features class __UpperCamelCase ( lowerCAmelCase_ ): A_ = MobileNetVaConfig A_ = load_tf_weights_in_mobilenet_va A_ = "mobilenet_v1" A_ = "pixel_values" A_ = False def __UpperCAmelCase ( self , __a ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __lowercase : Any = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowercase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a = True ): '''simple docstring''' super().__init__(__a ) __a : Optional[int] = config __a : str = 32 __a : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) __a : Union[str, Any] = MobileNetVaConvLayer( __a , in_channels=config.num_channels , out_channels=__a , kernel_size=3 , stride=2 , ) __a : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __a : Any = nn.ModuleList() for i in range(13 ): __a : Union[str, Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 __a : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=3 , stride=strides[i] , groups=__a , ) ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=1 , ) ) __a : Optional[int] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __UpperCAmelCase ( self , __a ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a : int = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __a : Union[str, Any] = self.conv_stem(__a ) __a : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __a : List[str] = layer_module(__a ) if output_hidden_states: __a : List[Any] = all_hidden_states + (hidden_states,) __a : str = hidden_states if self.pooler is not None: __a : Union[str, Any] = torch.flatten(self.pooler(__a ) , start_dim=1 ) else: __a : int = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__a , pooler_output=__a , hidden_states=__a , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Tuple = config.num_labels __a : Tuple = MobileNetVaModel(__a ) __a : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __a : Any = nn.Dropout(config.classifier_dropout_prob , inplace=__a ) __a : Any = nn.Linear(__a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Dict = self.mobilenet_va(__a , output_hidden_states=__a , return_dict=__a ) __a : List[str] = outputs.pooler_output if return_dict else outputs[1] __a : int = self.classifier(self.dropout(__a ) ) __a : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a : int = 'single_label_classification' else: __a : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __a : Optional[Any] = MSELoss() if self.num_labels == 1: __a : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __a : List[str] = CrossEntropyLoss() __a : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a : Tuple = BCEWithLogitsLoss() __a : Optional[int] = loss_fct(__a , __a ) if not return_dict: __a : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=__a , logits=__a , hidden_states=outputs.hidden_states , )
294
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" lowercase_ = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" lowercase_ = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): """simple docstring""" def snake_case__ ( self : Tuple )-> MetricInfo: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION,citation=_CITATION,inputs_description=_KWARGS_DESCRIPTION,features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string',id='token' ),id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string',id='token' ),id='sequence' ),id='references' ), } ),) def snake_case__ ( self : Any,lowercase_ : List[List[List[str]]],lowercase_ : List[List[str]],lowercase_ : int = 1,lowercase_ : int = 4,)-> Dict[str, float]: '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=lowercase_,hypotheses=lowercase_,min_len=lowercase_,max_len=lowercase_ ) }
7
from typing import Union import fire import torch from tqdm import tqdm def _snake_case( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str = "cpu" , SCREAMING_SNAKE_CASE__ : Union[str, None] = None ) -> None: '''simple docstring''' A__ = torch.load(SCREAMING_SNAKE_CASE__ , map_location=SCREAMING_SNAKE_CASE__ ) for k, v in tqdm(state_dict.items() ): if not isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): raise TypeError('FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin' ) A__ = v.half() if save_path is None: # overwrite src_path A__ = src_path torch.save(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": fire.Fire(convert)
7
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__ ): """simple docstring""" snake_case_ = ["""pixel_values"""] def __init__( self , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = PILImageResampling.BICUBIC , lowerCamelCase__ = True , lowerCamelCase__ = True , lowerCamelCase__ = 1 / 255 , lowerCamelCase__ = None , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Any: '''simple docstring''' super().__init__(**__a ) __lowerCamelCase = size if size is not None else {'height': 224, 'width': 224} __lowerCamelCase = get_size_dict(__a ) __lowerCamelCase = crop_size if crop_size is not None else {'height': 224, 'width': 224} __lowerCamelCase = get_size_dict(__a , default_to_square=__a , param_name='crop_size' ) __lowerCamelCase = do_resize __lowerCamelCase = do_rescale __lowerCamelCase = do_normalize __lowerCamelCase = do_center_crop __lowerCamelCase = crop_size __lowerCamelCase = size __lowerCamelCase = resample __lowerCamelCase = rescale_factor __lowerCamelCase = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __lowerCamelCase = image_std if image_std is not None else IMAGENET_DEFAULT_STD def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = PILImageResampling.BILINEAR , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = get_size_dict(__a ) if "shortest_edge" in size: __lowerCamelCase = get_resize_output_image_size(__a , size=size['shortest_edge'] , default_to_square=__a ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __lowerCamelCase = (size['height'], size['width']) else: raise ValueError(f"""Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}""" ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Any: '''simple docstring''' __lowerCamelCase = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(__a , size=(size['height'], size['width']) , data_format=__a , **__a ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ ) -> Dict: '''simple docstring''' return rescale(__a , scale=__a , data_format=__a , **__a ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Tuple: '''simple docstring''' return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = ChannelDimension.FIRST , **lowerCamelCase__ , ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase = do_resize if do_resize is not None else self.do_resize __lowerCamelCase = do_rescale if do_rescale is not None else self.do_rescale __lowerCamelCase = do_normalize if do_normalize is not None else self.do_normalize __lowerCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop __lowerCamelCase = crop_size if crop_size is not None else self.crop_size __lowerCamelCase = get_size_dict(__a , param_name='crop_size' , default_to_square=__a ) __lowerCamelCase = resample if resample is not None else self.resample __lowerCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCamelCase = image_mean if image_mean is not None else self.image_mean __lowerCamelCase = image_std if image_std is not None else self.image_std __lowerCamelCase = size if size is not None else self.size __lowerCamelCase = get_size_dict(__a ) if not is_batched(__a ): __lowerCamelCase = [images] if not valid_images(__a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. __lowerCamelCase = [to_numpy_array(__a ) for image in images] if do_resize: __lowerCamelCase = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_center_crop: __lowerCamelCase = [self.center_crop(image=__a , size=__a ) for image in images] if do_rescale: __lowerCamelCase = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: __lowerCamelCase = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] __lowerCamelCase = [to_channel_dimension_format(__a , __a ) for image in images] __lowerCamelCase = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a )
368
__A = { "joule": 1.0, "kilojoule": 10_00, "megajoule": 1_00_00_00, "gigajoule": 10_00_00_00_00, "wattsecond": 1.0, "watthour": 36_00, "kilowatthour": 3_60_00_00, "newtonmeter": 1.0, "calorie_nutr": 41_86.8, "kilocalorie_nutr": 4_18_68_00.00, "electronvolt": 1.6_0_2_1_7_6_6_3_4e-1_9, "britishthermalunit_it": 10_55.0_55_85, "footpound": 1.3_5_5_8_1_8, } def lowerCamelCase_ ( UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : float ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: __lowerCamelCase = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {', '.join(UpperCamelCase__ )}""" ) raise ValueError(UpperCamelCase__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
348
0
from collections.abc import Callable import numpy as np def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> np.array: '''simple docstring''' lowerCamelCase__ = int(np.ceil((x_end - xa) / step_size ) ) lowerCamelCase__ = np.zeros((n + 1,) ) lowerCamelCase__ = ya lowerCamelCase__ = xa for k in range(__a ): lowerCamelCase__ = y[k] + step_size * ode_func(__a ,y[k] ) lowerCamelCase__ = y[k] + ( (step_size / 2) * (ode_func(__a ,y[k] ) + ode_func(x + step_size ,__a )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
209
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py a__ = '''\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation", author = "Lin, Chin-Yew and Och, Franz Josef", booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics", month = "aug 23{--}aug 27", year = "2004", address = "Geneva, Switzerland", publisher = "COLING", url = "https://www.aclweb.org/anthology/C04-1072", pages = "501--507", } ''' a__ = '''\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation, the better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. ''' a__ = ''' Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: \'bleu\': bleu score, \'precisions\': geometric mean of n-gram precisions, \'brevity_penalty\': brevity penalty, \'length_ratio\': ratio of lengths, \'translation_length\': translation_length, \'reference_length\': reference_length Examples: >>> predictions = [ ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample ... ] >>> references = [ ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references) ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["bleu"]) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> Optional[int]: 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''' ), } ) , codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def __lowercase ( self , _a , _a , _a=4 , _a=False ) -> Optional[Any]: _a : List[Any] = compute_bleu( reference_corpus=_a , translation_corpus=_a , max_order=_a , smooth=_a ) ((_a) , (_a) , (_a) , (_a) , (_a) , (_a)) : Dict = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
235
0
'''simple docstring''' from math import ceil, sqrt def __magic_name__ ( A = 1_0_0_0_0_0_0 ) -> int: snake_case = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: snake_case = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: snake_case = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"{solution() = }")
357
'''simple docstring''' def __magic_name__ ( A ) -> float: return 1_0 - x * x def __magic_name__ ( A , A ) -> float: # Bolzano theory in order to find if there is a root between a and b if equation(A ) * equation(A ) >= 0: raise ValueError('Wrong space!' ) snake_case = a while (b - a) >= 0.01: # Find middle point snake_case = (a + b) / 2 # Check if middle point is root if equation(A ) == 0.0: break # Decide the side to repeat the steps if equation(A ) * equation(A ) < 0: snake_case = c else: snake_case = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
332
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowercase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase_ : Tuple =ShapEPipeline lowercase_ : List[Any] =['''prompt'''] lowercase_ : int =['''prompt'''] lowercase_ : Union[str, Any] =[ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] lowercase_ : Optional[int] =False @property def A__ ( self): return 3_2 @property def A__ ( self): return 3_2 @property def A__ ( self): return self.time_input_dim * 4 @property def A__ ( self): return 8 @property def A__ ( self): lowercase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') return tokenizer @property def A__ ( self): torch.manual_seed(0) lowercase = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=self.text_embedder_hidden_size ,projection_dim=self.text_embedder_hidden_size ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,) return CLIPTextModelWithProjection(A__) @property def A__ ( self): torch.manual_seed(0) lowercase = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_6, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 3_2, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase = PriorTransformer(**A__) return model @property def A__ ( self): torch.manual_seed(0) lowercase = { '''param_shapes''': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 1_2, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase = ShapERenderer(**A__) return model def A__ ( self): lowercase = self.dummy_prior lowercase = self.dummy_text_encoder lowercase = self.dummy_tokenizer lowercase = self.dummy_renderer lowercase = HeunDiscreteScheduler( beta_schedule='''exp''' ,num_train_timesteps=1_0_2_4 ,prediction_type='''sample''' ,use_karras_sigmas=A__ ,clip_sample=A__ ,clip_sample_range=1.0 ,) lowercase = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def A__ ( self ,A__ ,A__=0): if str(A__).startswith('''mps'''): lowercase = torch.manual_seed(A__) else: lowercase = torch.Generator(device=A__).manual_seed(A__) lowercase = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 3_2, '''output_type''': '''np''', } return inputs def A__ ( self): lowercase = '''cpu''' lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = pipe(**self.get_dummy_inputs(A__)) lowercase = output.images[0] lowercase = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) lowercase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def A__ ( self): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2]) def A__ ( self): lowercase = torch_device == '''cpu''' lowercase = True self._test_inference_batch_single_identical( batch_size=2 ,test_max_difference=A__ ,relax_max_difference=A__ ,) def A__ ( self): lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = 1 lowercase = 2 lowercase = self.get_dummy_inputs(A__) for key in inputs.keys(): if key in self.batch_params: lowercase = batch_size * [inputs[key]] lowercase = pipe(**A__ ,num_images_per_prompt=A__)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def A__ ( self): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self): lowercase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''') lowercase = ShapEPipeline.from_pretrained('''openai/shap-e''') lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = torch.Generator(device=A__).manual_seed(0) lowercase = pipe( '''a shark''' ,generator=A__ ,guidance_scale=15.0 ,num_inference_steps=6_4 ,frame_size=6_4 ,output_type='''np''' ,).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(A__ ,A__)
101
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase_ ) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _UpperCAmelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) _UpperCAmelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) _UpperCAmelCase : str = "audio" _UpperCAmelCase : str = "transcription" def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : int): if self.audio_column not in features: raise ValueError(F"Column {self.audio_column} is not present in features.") if not isinstance(features[self.audio_column] , lowerCAmelCase__): raise ValueError(F"Column {self.audio_column} is not an Audio type.") SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self) SCREAMING_SNAKE_CASE_: Optional[int] = self.input_schema.copy() SCREAMING_SNAKE_CASE_: Dict = features[self.audio_column] SCREAMING_SNAKE_CASE_: int = input_schema return task_template @property def _SCREAMING_SNAKE_CASE ( self : int): return {self.audio_column: "audio", self.transcription_column: "transcription"}
13
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _snake_case = { "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ["LlamaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ["LlamaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", "LlamaForSequenceClassification", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
371
"""simple docstring""" from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
324
0
"""simple docstring""" import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE =get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right __SCREAMING_SNAKE_CASE =25_6047 __SCREAMING_SNAKE_CASE =25_6145 @require_sentencepiece @require_tokenizers class UpperCamelCase ( _snake_case , unittest.TestCase ): lowercase = NllbTokenizer lowercase = NllbTokenizerFast lowercase = True lowercase = True lowercase = {} def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowercase_ : List[Any] = NllbTokenizer(_lowerCamelCase ,keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Any = NllbTokenizer(_lowerCamelCase ,keep_accents=_lowerCamelCase ) lowercase_ : List[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(_lowerCamelCase ,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) ,[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] ,) lowercase_ : Any = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _lowerCamelCase ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] ,) lowercase_ : Any = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] ,) lowercase_ : Any = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] ,) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : Any = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-nllb''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : Any = self.rust_tokenizer_class.from_pretrained(_lowerCamelCase ,**_lowerCamelCase ) lowercase_ : Any = self.tokenizer_class.from_pretrained(_lowerCamelCase ,**_lowerCamelCase ) lowercase_ : List[Any] = tempfile.mkdtemp() lowercase_ : List[Any] = tokenizer_r.save_pretrained(_lowerCamelCase ) lowercase_ : Optional[int] = tokenizer_p.save_pretrained(_lowerCamelCase ) # 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 ) ) lowercase_ : List[str] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(_lowerCamelCase ,_lowerCamelCase ) # Checks everything loads correctly in the same way lowercase_ : str = tokenizer_r.from_pretrained(_lowerCamelCase ) lowercase_ : str = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase ,_lowerCamelCase ) ) shutil.rmtree(_lowerCamelCase ) # Save tokenizer rust, legacy_format=True lowercase_ : int = tempfile.mkdtemp() lowercase_ : str = tokenizer_r.save_pretrained(_lowerCamelCase ,legacy_format=_lowerCamelCase ) lowercase_ : List[Any] = tokenizer_p.save_pretrained(_lowerCamelCase ) # Checks it save with the same files self.assertSequenceEqual(_lowerCamelCase ,_lowerCamelCase ) # Checks everything loads correctly in the same way lowercase_ : List[Any] = tokenizer_r.from_pretrained(_lowerCamelCase ) lowercase_ : Optional[int] = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase ,_lowerCamelCase ) ) shutil.rmtree(_lowerCamelCase ) # Save tokenizer rust, legacy_format=False lowercase_ : Optional[int] = tempfile.mkdtemp() lowercase_ : str = tokenizer_r.save_pretrained(_lowerCamelCase ,legacy_format=_lowerCamelCase ) lowercase_ : List[str] = tokenizer_p.save_pretrained(_lowerCamelCase ) # 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 lowercase_ : Tuple = tokenizer_r.from_pretrained(_lowerCamelCase ) lowercase_ : Optional[Any] = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase ,_lowerCamelCase ) ) shutil.rmtree(_lowerCamelCase ) @require_torch def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' if not self.test_seqaseq: return lowercase_ : Union[str, Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): # Longer text that will definitely require truncation. lowercase_ : int = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for''' ''' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons''' ''' will only worsen the violence and misery for millions of people.''', ] lowercase_ : Tuple = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al''' ''' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi''' ''' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] try: lowercase_ : Optional[Any] = tokenizer.prepare_seqaseq_batch( src_texts=_lowerCamelCase ,tgt_texts=_lowerCamelCase ,max_length=3 ,max_target_length=10 ,return_tensors='pt' ,src_lang='eng_Latn' ,tgt_lang='ron_Latn' ,) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] ,3 ) self.assertEqual(batch.labels.shape[1] ,10 ) # max_target_length will default to max_length if not specified lowercase_ : List[Any] = tokenizer.prepare_seqaseq_batch( _lowerCamelCase ,tgt_texts=_lowerCamelCase ,max_length=3 ,return_tensors='pt' ) self.assertEqual(batch.input_ids.shape[1] ,3 ) self.assertEqual(batch.labels.shape[1] ,3 ) lowercase_ : int = tokenizer.prepare_seqaseq_batch( src_texts=_lowerCamelCase ,max_length=3 ,max_target_length=10 ,return_tensors='pt' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] ,3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] ,3 ) self.assertNotIn('decoder_input_ids' ,_lowerCamelCase ) @unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' ) def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' pass def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : Optional[Any] = [AddedToken('<special>' ,lstrip=_lowerCamelCase )] lowercase_ : List[Any] = self.rust_tokenizer_class.from_pretrained( _lowerCamelCase ,additional_special_tokens=_lowerCamelCase ,**_lowerCamelCase ) lowercase_ : List[str] = tokenizer_r.encode('Hey this is a <special> token' ) lowercase_ : Optional[Any] = tokenizer_r.encode('<special>' ,add_special_tokens=_lowerCamelCase )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: lowercase_ : int = self.rust_tokenizer_class.from_pretrained( _lowerCamelCase ,additional_special_tokens=_lowerCamelCase ,**_lowerCamelCase ,) lowercase_ : str = self.tokenizer_class.from_pretrained( _lowerCamelCase ,additional_special_tokens=_lowerCamelCase ,**_lowerCamelCase ) lowercase_ : Any = tokenizer_p.encode('Hey this is a <special> token' ) lowercase_ : Tuple = tokenizer_cr.encode('Hey this is a <special> token' ) self.assertEqual(_lowerCamelCase ,_lowerCamelCase ) self.assertEqual(_lowerCamelCase ,_lowerCamelCase ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase ( unittest.TestCase ): lowercase = 'facebook/nllb-200-distilled-600M' lowercase = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] lowercase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] lowercase = [ 2_5_6_0_4_7, 1_6_2_9_7, 1_3_4_4_0_8, 8_1_6_5, 2_4_8_0_6_6, 1_4_7_3_4, 9_5_0, 1_1_3_5, 1_0_5_7_2_1, 3_5_7_3, 8_3, 2_7_3_5_2, 1_0_8, 4_9_4_8_6, 2, ] @classmethod def _UpperCAmelCase ( cls ) -> List[Any]: '''simple docstring''' lowercase_ : NllbTokenizer = NllbTokenizer.from_pretrained( cls.checkpoint_name ,src_lang='eng_Latn' ,tgt_lang='ron_Latn' ) lowercase_ : Union[str, Any] = 1 return cls def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] ,25_6001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] ,25_6002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] ,25_6057 ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : Any = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens ,_lowerCamelCase ) def _UpperCAmelCase ( self ) -> int: '''simple docstring''' self.assertIn(_lowerCamelCase ,self.tokenizer.all_special_ids ) # fmt: off lowercase_ : Union[str, Any] = [RO_CODE, 4254, 9_8068, 11_2923, 3_9072, 3909, 713, 10_2767, 26, 1_7314, 3_5642, 1_4683, 3_3118, 2022, 6_6987, 2, 25_6047] # fmt: on lowercase_ : List[Any] = self.tokenizer.decode(_lowerCamelCase ,skip_special_tokens=_lowerCamelCase ) lowercase_ : Any = self.tokenizer.decode(generated_ids[1:] ,skip_special_tokens=_lowerCamelCase ) self.assertEqual(_lowerCamelCase ,_lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token ,_lowerCamelCase ) def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Optional[int] = ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] ,_lowerCamelCase ) lowercase_ : Dict = 10 lowercase_ : int = self.tokenizer(_lowerCamelCase ,max_length=_lowerCamelCase ,truncation=_lowerCamelCase ).input_ids[0] self.assertEqual(ids[-1] ,2 ) self.assertEqual(ids[0] ,_lowerCamelCase ) self.assertEqual(len(_lowerCamelCase ) ,_lowerCamelCase ) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) ,[25_6203, 3] ) def _UpperCAmelCase ( self ) -> str: '''simple docstring''' lowercase_ : str = tempfile.mkdtemp() lowercase_ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_lowerCamelCase ) lowercase_ : int = NllbTokenizer.from_pretrained(_lowerCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids ,_lowerCamelCase ) @require_torch def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : List[str] = self.tokenizer( self.src_text ,text_target=self.tgt_text ,padding=_lowerCamelCase ,truncation=_lowerCamelCase ,max_length=len(self.expected_src_tokens ) ,return_tensors='pt' ,) lowercase_ : str = shift_tokens_right( batch['labels'] ,self.tokenizer.pad_token_id ,self.tokenizer.lang_code_to_id['ron_Latn'] ) self.assertIsInstance(_lowerCamelCase ,_lowerCamelCase ) self.assertEqual((2, 15) ,batch.input_ids.shape ) self.assertEqual((2, 15) ,batch.attention_mask.shape ) lowercase_ : str = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens ,_lowerCamelCase ) self.assertEqual(_lowerCamelCase ,batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens ,[EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens ,[self.tokenizer.eos_token_id] ) def _UpperCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ : Tuple = self.tokenizer(self.src_text ,padding=_lowerCamelCase ,truncation=_lowerCamelCase ,max_length=3 ,return_tensors='pt' ) lowercase_ : Any = self.tokenizer( text_target=self.tgt_text ,padding=_lowerCamelCase ,truncation=_lowerCamelCase ,max_length=10 ,return_tensors='pt' ) lowercase_ : List[str] = targets['''input_ids'''] lowercase_ : Union[str, Any] = shift_tokens_right( _lowerCamelCase ,self.tokenizer.pad_token_id ,decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] ,) self.assertEqual(batch.input_ids.shape[1] ,3 ) self.assertEqual(batch.decoder_input_ids.shape[1] ,10 ) @require_torch def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' lowercase_ : List[str] = self.tokenizer._build_translation_inputs( 'A test' ,return_tensors='pt' ,src_lang='eng_Latn' ,tgt_lang='fra_Latn' ) self.assertEqual( nested_simplify(_lowerCamelCase ) ,{ # A, test, EOS, en_XX 'input_ids': [[25_6047, 70, 7356, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_6057, } ,) @require_torch def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : Optional[Any] = True lowercase_ : int = self.tokenizer( 'UN Chief says there is no military solution in Syria' ,src_lang='eng_Latn' ,tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids ,[1_6297, 13_4408, 2_5653, 6370, 248, 254, 10_3929, 9_4995, 108, 4_9486, 2, 25_6047] ) lowercase_ : Optional[int] = False lowercase_ : Optional[Any] = self.tokenizer( 'UN Chief says there is no military solution in Syria' ,src_lang='eng_Latn' ,tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids ,[25_6047, 1_6297, 13_4408, 2_5653, 6370, 248, 254, 10_3929, 9_4995, 108, 4_9486, 2] )
213
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers snake_case : Union[str, Any] = '''python tqdm regex requests packaging filelock numpy tokenizers'''.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('''dataclasses''') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('''importlib_metadata''') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def __lowerCamelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=None ): """simple docstring""" require_version(deps[pkg] , UpperCAmelCase_ )
94
0
'''simple docstring''' def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) lowercase__ : Any = (boundary[1] - boundary[0]) / steps lowercase__ : List[str] = boundary[0] lowercase__ : List[Any] = boundary[1] lowercase__ : Any = make_points(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) lowercase__ : Optional[Any] = 0.0 y += (h / 2.0) * f(UpperCAmelCase ) for i in x_i: # print(i) y += h * f(UpperCAmelCase ) y += (h / 2.0) * f(UpperCAmelCase ) return y def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): lowercase__ : Any = a + h while x < (b - h): yield x lowercase__ : Optional[Any] = x + h def __UpperCamelCase ( UpperCAmelCase ): # enter your function here lowercase__ : str = (x - 0) * (x - 0) return y def __UpperCamelCase ( ): lowercase__ : Optional[Any] = 0.0 # Lower bound of integration lowercase__ : Optional[int] = 1.0 # Upper bound of integration lowercase__ : List[Any] = 1_0.0 # define number of steps or resolution lowercase__ : Any = [a, b] # define boundary of integration lowercase__ : List[Any] = method_a(UpperCAmelCase , UpperCAmelCase ) print(F"""y = {y}""" ) if __name__ == "__main__": main()
214
'''simple docstring''' import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __a: List[str] = logging.get_logger(__name__) __a: int = """▁""" __a: Optional[int] = {"""vocab_file""": """prophetnet.tokenizer"""} __a: Optional[int] = { """vocab_file""": { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer""" ), } } __a: List[str] = { """microsoft/xprophetnet-large-wiki100-cased""": {"""do_lower_case""": False}, } __a: Tuple = { """microsoft/xprophetnet-large-wiki100-cased""": 5_12, } def __UpperCamelCase ( UpperCAmelCase ): lowercase__ : Dict = collections.OrderedDict() with open(UpperCAmelCase , '''r''' , encoding='''utf-8''' ) as reader: lowercase__ : List[Any] = reader.readlines() for index, token in enumerate(UpperCAmelCase ): lowercase__ : List[Any] = token.rstrip('''\n''' ) lowercase__ : Tuple = index return vocab class UpperCAmelCase ( a__ ): '''simple docstring''' SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask"] def __init__( self , __lowerCAmelCase , __lowerCAmelCase="[SEP]" , __lowerCAmelCase="[SEP]" , __lowerCAmelCase="[SEP]" , __lowerCAmelCase="[UNK]" , __lowerCAmelCase="[PAD]" , __lowerCAmelCase="[CLS]" , __lowerCAmelCase="[MASK]" , __lowerCAmelCase = None , **__lowerCAmelCase , ) -> None: lowercase__ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise lowercase__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowerCAmelCase ) ) lowercase__ : Optional[int] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # put special tokens and [unused] tokens into the vocab lowercase__ : str = {'''[PAD]''': 0, '''[CLS]''': 1, '''[SEP]''': 2, '''[UNK]''': 3, '''[MASK]''': 4} for i in range(10 ): lowercase__ : Tuple = F"""[unused{i}]""" lowercase__ : List[Any] = 5 + i # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab lowercase__ : Optional[Any] = 12 lowercase__ : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} for k in self.fairseq_tokens_to_ids.keys(): self.unique_no_split_tokens.append(__lowerCAmelCase ) def __getstate__( self ) -> Union[str, Any]: lowercase__ : Dict = self.__dict__.copy() lowercase__ : Optional[Any] = None return state def __setstate__( self , __lowerCAmelCase ) -> Dict: lowercase__ : Any = d try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase__ : List[Any] = {} lowercase__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCAmelCase , token_ids_a=__lowerCAmelCase , already_has_special_tokens=__lowerCAmelCase ) if token_ids_a is None: return ([0] * len(__lowerCAmelCase )) + [1] return ([0] * len(__lowerCAmelCase )) + [1] + ([0] * len(__lowerCAmelCase )) + [1] def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None ) -> List[int]: lowercase__ : List[str] = [self.sep_token_id] if token_ids_a is None: return len(token_ids_a + sep ) * [0] return len(token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _lowerCAmelCase( self ) -> List[Any]: return len(self.sp_model ) + self.fairseq_offset def _lowerCAmelCase( self ) -> List[str]: lowercase__ : str = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowerCAmelCase( self , __lowerCAmelCase ) -> str: return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> Optional[Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase__ : Tuple = self.sp_model.PieceToId(__lowerCAmelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _lowerCAmelCase( self , __lowerCAmelCase ) -> str: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> Union[str, Any]: lowercase__ : Optional[Any] = ''''''.join(__lowerCAmelCase ).replace(__lowerCAmelCase , ''' ''' ).strip() return out_string def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase__ : 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: lowercase__ : List[Any] = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (out_vocab_file,) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.sep_token_id] lowercase__ : str = [self.sep_token_id] return token_ids_a + sep + token_ids_a + sep
214
1
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
33
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _UpperCAmelCase : Optional[int] = logging.get_logger(__name__) _UpperCAmelCase : Any = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } _UpperCAmelCase : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[Any]: for attribute in key.split('.' ): lowerCamelCase__ : int = getattr(_UpperCAmelCase , _UpperCAmelCase ) if weight_type is not None: lowerCamelCase__ : Optional[int] = getattr(_UpperCAmelCase , _UpperCAmelCase ).shape else: lowerCamelCase__ : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": lowerCamelCase__ : Dict = value elif weight_type == "weight_g": lowerCamelCase__ : List[Any] = value elif weight_type == "weight_v": lowerCamelCase__ : List[str] = value elif weight_type == "bias": lowerCamelCase__ : Union[str, Any] = value else: lowerCamelCase__ : Optional[int] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase__ : Optional[int] = [] lowerCamelCase__ : str = fairseq_model.state_dict() lowerCamelCase__ : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight lowerCamelCase__ : List[Any] = None for name, value in fairseq_dict.items(): lowerCamelCase__ : List[Any] = False if "conv_layers" in name: load_conv_layer( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , hf_model.config.feat_extract_norm == 'group' , ) lowerCamelCase__ : List[Any] = True elif name.split('.' )[0] == "proj": lowerCamelCase__ : Union[str, Any] = fairseq_model.proj lowerCamelCase__ : Dict = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: lowerCamelCase__ : Optional[Any] = True if "*" in mapped_key: lowerCamelCase__ : Optional[Any] = name.split(_UpperCAmelCase )[0].split('.' )[-2] lowerCamelCase__ : List[str] = mapped_key.replace('*' , _UpperCAmelCase ) if "weight_g" in name: lowerCamelCase__ : int = 'weight_g' elif "weight_v" in name: lowerCamelCase__ : Union[str, Any] = 'weight_v' elif "bias" in name: lowerCamelCase__ : List[Any] = 'bias' elif "weight" in name: lowerCamelCase__ : List[Any] = 'weight' else: lowerCamelCase__ : Tuple = None set_recursively(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) continue if not is_used: unused_weights.append(_UpperCAmelCase ) logger.warning(F"""Unused weights: {unused_weights}""" ) return proj_weight def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase__ : Dict = full_name.split('conv_layers.' )[-1] lowerCamelCase__ : Optional[Any] = name.split('.' ) lowerCamelCase__ : Union[str, Any] = int(items[0] ) lowerCamelCase__ : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) lowerCamelCase__ : Optional[Any] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) lowerCamelCase__ : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) lowerCamelCase__ : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) lowerCamelCase__ : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> List[Any]: lowerCamelCase__ : Dict = emb.weight.shape lowerCamelCase__ : List[str] = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase ) lowerCamelCase__ : List[Any] = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> int: with open(_UpperCAmelCase , 'r' , encoding='utf-8' ) as f: lowerCamelCase__ : Union[str, Any] = f.readlines() lowerCamelCase__ : str = [line.split(' ' )[0] for line in lines] lowerCamelCase__ : str = len(_UpperCAmelCase ) lowerCamelCase__ : Tuple = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(_UpperCAmelCase , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) -> Tuple: lowerCamelCase__ : str = WavaVecaConfig.from_pretrained(_UpperCAmelCase ) lowerCamelCase__ : List[Any] = SpeechaTextaConfig.from_pretrained( _UpperCAmelCase , vocab_size=_UpperCAmelCase , decoder_layers=_UpperCAmelCase , do_stable_layer_norm=_UpperCAmelCase ) lowerCamelCase__ : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ) lowerCamelCase__ : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) lowerCamelCase__ : List[Any] = model[0].eval() # set weights for wav2vec2 encoder lowerCamelCase__ : List[str] = WavaVecaModel(_UpperCAmelCase ) lowerCamelCase__ : Tuple = recursively_load_weights_wavaveca(model.encoder , _UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = SpeechaTextaForCausalLM(_UpperCAmelCase ) lowerCamelCase__ : int = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_UpperCAmelCase ) # set output linear layer unexpected_keys.remove('embed_out' ) lowerCamelCase__ : int = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) lowerCamelCase__ : Union[str, Any] = SpeechEncoderDecoderModel(encoder=_UpperCAmelCase , decoder=_UpperCAmelCase ) lowerCamelCase__ : List[Any] = False # add projection layer lowerCamelCase__ : str = nn.Parameter(projection_layer.weight ) lowerCamelCase__ : Optional[int] = nn.Parameter(projection_layer.bias ) lowerCamelCase__ : Dict = create_vocab_dict(_UpperCAmelCase ) with open(os.path.join(_UpperCAmelCase , 'vocab.json' ) , 'w' ) as fp: json.dump(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : List[Any] = SpeechaTextaTokenizer(os.path.join(_UpperCAmelCase , 'vocab.json' ) ) tokenizer.save_pretrained(_UpperCAmelCase ) lowerCamelCase__ : Dict = hf_wavavec.config.to_dict() lowerCamelCase__ : Dict = tokenizer.pad_token_id lowerCamelCase__ : int = tokenizer.bos_token_id lowerCamelCase__ : str = tokenizer.eos_token_id lowerCamelCase__ : Tuple = 'speech_to_text_2' lowerCamelCase__ : Optional[Any] = 'wav2vec2' lowerCamelCase__ : Dict = SpeechEncoderDecoderConfig.from_dict(_UpperCAmelCase ) hf_wavavec.save_pretrained(_UpperCAmelCase ) feature_extractor.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": _UpperCAmelCase : Dict = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument( """--encoder_config_path""", default="""facebook/wav2vec2-large-lv60""", type=str, help="""Path to hf encoder wav2vec2 checkpoint config""", ) parser.add_argument( """--decoder_config_path""", default="""facebook/s2t-small-mustc-en-fr-st""", type=str, help="""Path to hf decoder s2t checkpoint config""", ) parser.add_argument("""--vocab_size""", default=1_02_24, type=int, help="""Vocab size of decoder""") parser.add_argument("""--num_decoder_layers""", default=7, type=int, help="""Number of decoder layers""") _UpperCAmelCase : Dict = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
365
from collections import deque class lowerCAmelCase : def __init__( self : str , UpperCAmelCase : str , UpperCAmelCase : int , UpperCAmelCase : int ) -> None: lowerCamelCase__ : Optional[int] = process_name # process name lowerCamelCase__ : Optional[int] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time lowerCamelCase__ : str = arrival_time lowerCamelCase__ : List[Any] = burst_time # remaining burst time lowerCamelCase__ : Any = 0 # total time of the process wait in ready queue lowerCamelCase__ : Tuple = 0 # time from arrival time to completion time class lowerCAmelCase : def __init__( self : List[str] , UpperCAmelCase : int , UpperCAmelCase : list[int] , UpperCAmelCase : deque[Process] , UpperCAmelCase : int , ) -> None: # total number of mlfq's queues lowerCamelCase__ : Optional[int] = number_of_queues # time slice of queues that round robin algorithm applied lowerCamelCase__ : List[str] = time_slices # unfinished process is in this ready_queue lowerCamelCase__ : List[str] = queue # current time lowerCamelCase__ : Optional[Any] = current_time # finished process is in this sequence queue lowerCamelCase__ : deque[Process] = deque() def A_ ( self : Tuple ) -> list[str]: lowerCamelCase__ : Union[str, Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def A_ ( self : Tuple , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : Tuple = [] for i in range(len(UpperCAmelCase ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def A_ ( self : Union[str, Any] , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : int = [] for i in range(len(UpperCAmelCase ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def A_ ( self : Optional[int] , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : Tuple = [] for i in range(len(UpperCAmelCase ) ): completion_times.append(queue[i].stop_time ) return completion_times def A_ ( self : str , UpperCAmelCase : deque[Process] ) -> list[int]: return [q.burst_time for q in queue] def A_ ( self : int , UpperCAmelCase : Process ) -> int: process.waiting_time += self.current_time - process.stop_time return process.waiting_time def A_ ( self : Optional[int] , UpperCAmelCase : deque[Process] ) -> deque[Process]: lowerCamelCase__ : deque[Process] = deque() # sequence deque of finished process while len(UpperCAmelCase ) != 0: lowerCamelCase__ : List[Any] = 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(UpperCAmelCase ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 lowerCamelCase__ : Optional[int] = 0 # set the process's turnaround time because it is finished lowerCamelCase__ : Union[str, Any] = self.current_time - cp.arrival_time # set the completion time lowerCamelCase__ : Any = self.current_time # add the process to queue that has finished queue finished.append(UpperCAmelCase ) self.finish_queue.extend(UpperCAmelCase ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def A_ ( self : str , UpperCAmelCase : deque[Process] , UpperCAmelCase : int ) -> tuple[deque[Process], deque[Process]]: lowerCamelCase__ : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(UpperCAmelCase ) ): lowerCamelCase__ : Dict = 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(UpperCAmelCase ) # 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 lowerCamelCase__ : List[str] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(UpperCAmelCase ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished lowerCamelCase__ : Any = 0 # set the finish time lowerCamelCase__ : int = self.current_time # update the process' turnaround time because it is finished lowerCamelCase__ : Dict = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(UpperCAmelCase ) self.finish_queue.extend(UpperCAmelCase ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def A_ ( self : Dict ) -> deque[Process]: # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): lowerCamelCase__ , lowerCamelCase__ : Any = 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 _UpperCAmelCase : List[str] = Process("""P1""", 0, 53) _UpperCAmelCase : Union[str, Any] = Process("""P2""", 0, 17) _UpperCAmelCase : int = Process("""P3""", 0, 68) _UpperCAmelCase : str = Process("""P4""", 0, 24) _UpperCAmelCase : Optional[int] = 3 _UpperCAmelCase : Optional[Any] = [17, 25] _UpperCAmelCase : Optional[int] = 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])}) _UpperCAmelCase : Tuple = Process("""P1""", 0, 53) _UpperCAmelCase : Any = Process("""P2""", 0, 17) _UpperCAmelCase : Any = Process("""P3""", 0, 68) _UpperCAmelCase : List[Any] = Process("""P4""", 0, 24) _UpperCAmelCase : List[str] = 3 _UpperCAmelCase : Optional[int] = [17, 25] _UpperCAmelCase : Optional[int] = deque([Pa, Pa, Pa, Pa]) _UpperCAmelCase : Union[str, Any] = MLFQ(number_of_queues, time_slices, queue, 0) _UpperCAmelCase : Dict = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( F"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( F"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( F"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
45
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case =logging.get_logger(__name__) __snake_case ={ """microsoft/swin-tiny-patch4-window7-224""": ( """https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json""" ), # See all Swin models at https://huggingface.co/models?filter=swin } class UpperCAmelCase_ ( __lowercase , __lowercase ): lowerCamelCase : Union[str, Any] = '''swin''' lowerCamelCase : Optional[Any] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : int , UpperCAmelCase__ : List[Any]=2_2_4 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Dict=3 , UpperCAmelCase__ : Union[str, Any]=9_6 , UpperCAmelCase__ : Any=[2, 2, 6, 2] , UpperCAmelCase__ : List[str]=[3, 6, 1_2, 2_4] , UpperCAmelCase__ : List[Any]=7 , UpperCAmelCase__ : Dict=4.0 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[Any]=1E-5 , UpperCAmelCase__ : List[str]=3_2 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Dict , ) -> int: 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 lowerCAmelCase = encoder_stride # 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 ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Dict = version.parse('''1.11''' ) @property def __UpperCAmelCase ( self : Dict ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __UpperCAmelCase ( self : Dict ) -> float: return 1E-4
4
'''simple docstring''' class UpperCAmelCase_ : def __init__( self : List[str] , UpperCAmelCase__ : list[int] ) -> None: lowerCAmelCase = len(UpperCAmelCase__ ) lowerCAmelCase = [0] * len_array if len_array > 0: lowerCAmelCase = array[0] for i in range(1 , UpperCAmelCase__ ): lowerCAmelCase = self.prefix_sum[i - 1] + array[i] def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __UpperCAmelCase ( self : int , UpperCAmelCase__ : int ) -> bool: lowerCAmelCase = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(UpperCAmelCase__ ) return False if __name__ == "__main__": import doctest doctest.testmod()
4
1
import math import unittest def _snake_case ( A ) -> bool: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" 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 class a__ ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self ) -> int: self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: with self.assertRaises(_a ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , '''Zero doesn\'t have any positive factors, primes must have exactly two.''' , ) self.assertFalse( is_prime(1 ) , '''One only has 1 positive factor, primes must have exactly two.''' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
361
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class a__ ( a__ ): '''simple docstring''' lowercase__ : torch.FloatTensor class a__ ( a__ , a__ ): '''simple docstring''' @register_to_config def __init__( self , lowerCamelCase_ = 6_55_36 , lowerCamelCase_ = None , lowerCamelCase_ = 2 , lowerCamelCase_ = 2 , lowerCamelCase_ = 0 , lowerCamelCase_ = "fourier" , lowerCamelCase_ = True , lowerCamelCase_ = False , lowerCamelCase_ = 0.0 , lowerCamelCase_ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , lowerCamelCase_ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , lowerCamelCase_ = "UNetMidBlock1D" , lowerCamelCase_ = None , lowerCamelCase_ = (32, 32, 64) , lowerCamelCase_ = None , lowerCamelCase_ = 8 , lowerCamelCase_ = 1 , lowerCamelCase_ = False , ) -> Optional[int]: super().__init__() lowerCAmelCase__ = sample_size # time if time_embedding_type == "fourier": lowerCAmelCase__ = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=lowerCamelCase_ , log=lowerCamelCase_ , flip_sin_to_cos=lowerCamelCase_ ) lowerCAmelCase__ = 2 * block_out_channels[0] elif time_embedding_type == "positional": lowerCAmelCase__ = Timesteps( block_out_channels[0] , flip_sin_to_cos=lowerCamelCase_ , downscale_freq_shift=lowerCamelCase_ ) lowerCAmelCase__ = block_out_channels[0] if use_timestep_embedding: lowerCAmelCase__ = block_out_channels[0] * 4 lowerCAmelCase__ = TimestepEmbedding( in_channels=lowerCamelCase_ , time_embed_dim=lowerCamelCase_ , act_fn=lowerCamelCase_ , out_dim=block_out_channels[0] , ) lowerCAmelCase__ = nn.ModuleList([] ) lowerCAmelCase__ = None lowerCAmelCase__ = nn.ModuleList([] ) lowerCAmelCase__ = None # down lowerCAmelCase__ = in_channels for i, down_block_type in enumerate(lowerCamelCase_ ): lowerCAmelCase__ = output_channel lowerCAmelCase__ = block_out_channels[i] if i == 0: input_channel += extra_in_channels lowerCAmelCase__ = i == len(lowerCamelCase_ ) - 1 lowerCAmelCase__ = get_down_block( lowerCamelCase_ , num_layers=lowerCamelCase_ , in_channels=lowerCamelCase_ , out_channels=lowerCamelCase_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(lowerCamelCase_ ) # mid lowerCAmelCase__ = get_mid_block( lowerCamelCase_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=lowerCamelCase_ , add_downsample=lowerCamelCase_ , ) # up lowerCAmelCase__ = list(reversed(lowerCamelCase_ ) ) lowerCAmelCase__ = reversed_block_out_channels[0] if out_block_type is None: lowerCAmelCase__ = out_channels else: lowerCAmelCase__ = block_out_channels[0] for i, up_block_type in enumerate(lowerCamelCase_ ): lowerCAmelCase__ = output_channel lowerCAmelCase__ = ( reversed_block_out_channels[i + 1] if i < len(lowerCamelCase_ ) - 1 else final_upsample_channels ) lowerCAmelCase__ = i == len(lowerCamelCase_ ) - 1 lowerCAmelCase__ = get_up_block( lowerCamelCase_ , num_layers=lowerCamelCase_ , in_channels=lowerCamelCase_ , out_channels=lowerCamelCase_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(lowerCamelCase_ ) lowerCAmelCase__ = output_channel # out lowerCAmelCase__ = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) lowerCAmelCase__ = get_out_block( out_block_type=lowerCamelCase_ , num_groups_out=lowerCamelCase_ , embed_dim=block_out_channels[0] , out_channels=lowerCamelCase_ , act_fn=lowerCamelCase_ , fc_dim=block_out_channels[-1] // 4 , ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = True , ) -> Union[UNetaDOutput, Tuple]: lowerCAmelCase__ = timestep if not torch.is_tensor(lowerCamelCase_ ): lowerCAmelCase__ = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(lowerCamelCase_ ) and len(timesteps.shape ) == 0: lowerCAmelCase__ = timesteps[None].to(sample.device ) lowerCAmelCase__ = self.time_proj(lowerCamelCase_ ) if self.config.use_timestep_embedding: lowerCAmelCase__ = self.time_mlp(lowerCamelCase_ ) else: lowerCAmelCase__ = timestep_embed[..., None] lowerCAmelCase__ = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) lowerCAmelCase__ = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down lowerCAmelCase__ = () for downsample_block in self.down_blocks: lowerCAmelCase__ , lowerCAmelCase__ = downsample_block(hidden_states=lowerCamelCase_ , temb=lowerCamelCase_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: lowerCAmelCase__ = self.mid_block(lowerCamelCase_ , lowerCamelCase_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): lowerCAmelCase__ = down_block_res_samples[-1:] lowerCAmelCase__ = down_block_res_samples[:-1] lowerCAmelCase__ = upsample_block(lowerCamelCase_ , res_hidden_states_tuple=lowerCamelCase_ , temb=lowerCamelCase_ ) # 5. post-process if self.out_block: lowerCAmelCase__ = self.out_block(lowerCamelCase_ , lowerCamelCase_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=lowerCamelCase_ )
228
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 lowercase ( _snake_case : str ) ->Tuple: """simple docstring""" __snake_case : Tuple = [ '''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(_snake_case , _snake_case ) def lowercase ( _snake_case : Tuple ) ->Tuple: """simple docstring""" __snake_case , __snake_case : str = emb.weight.shape __snake_case : int = nn.Linear(_snake_case , _snake_case , bias=_snake_case ) __snake_case : Union[str, Any] = emb.weight.data return lin_layer def lowercase ( _snake_case : List[Any] , _snake_case : Tuple=None ) ->Dict: """simple docstring""" __snake_case : Optional[Any] = {} for old_key in state_dict.keys(): __snake_case : List[Any] = old_key if "moe_layer.experts." in key: if expert_idx is not None: __snake_case : Optional[int] = key.replace('''moe_layer.experts.0''' , f"""ffn.experts.expert_{expert_idx}""" ) else: __snake_case : Tuple = key.replace('''moe_layer.experts.''' , '''ffn.experts.expert_''' ) if "gate" in key: __snake_case : Union[str, Any] = key.replace('''.moe_layer.gate.wg''' , '''.ffn.router.classifier''' ) if "fc2" and "experts" not in key: __snake_case : List[Any] = key.replace('''.fc2.''' , '''.ffn.fc2.''' ) if "fc1" and "experts" not in key: __snake_case : Union[str, Any] = key.replace('''.fc1.''' , '''.ffn.fc1.''' ) if ".encoder_attn." in key: __snake_case : Optional[int] = key.replace('''.encoder_attn.''' , '''.cross_attention.''' ) if "encoder_attn_layer_norm" in key: __snake_case : int = key.replace('''encoder_attn_layer_norm''' , '''cross_attention_layer_norm''' ) if "final_layer_norm" in key: __snake_case : List[str] = key.replace('''final_layer_norm''' , '''ff_layer_norm''' ) __snake_case : Union[str, Any] = state_dict[old_key] return new_dict def lowercase ( _snake_case : List[Any] , _snake_case : Union[str, Any] , _snake_case : str , _snake_case : int , _snake_case : str = WEIGHTS_NAME ) ->Tuple: """simple docstring""" __snake_case : int = [] __snake_case : Any = 0 os.makedirs(_snake_case , exist_ok=_snake_case ) for expert in range(_snake_case ): __snake_case : Tuple = switch_checkpoint_path + f"""-rank-{expert}.pt""" if os.path.isfile(_snake_case ): __snake_case : Dict = torch.load(_snake_case )['''model'''] remove_ignore_keys_(_snake_case ) __snake_case : str = rename_fairseq_keys(_snake_case , _snake_case ) __snake_case : Union[str, Any] = os.path.join( _snake_case , weights_name.replace('''.bin''' , f"""-{len(_snake_case )+1:05d}-of-???.bin""" ) ) torch.save(_snake_case , _snake_case ) 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(_snake_case )[0]].dtype ) # Add the last block __snake_case : Dict = os.path.join(_snake_case , weights_name.replace('''.bin''' , f"""-{len(_snake_case )+1:05d}-of-???.bin""" ) ) __snake_case : Optional[Any] = torch.load(switch_checkpoint_path + '''-shared.pt''' )['''model'''] remove_ignore_keys_(_snake_case ) __snake_case : str = rename_fairseq_keys(_snake_case , _snake_case ) __snake_case : Any = 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(_snake_case ) == 1: __snake_case : List[str] = os.path.join(_snake_case , _snake_case ) torch.save(_snake_case , _snake_case ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(_snake_case , _snake_case ) # Otherwise, let's build the index __snake_case : Union[str, Any] = {} for idx, shard in enumerate(_snake_case ): __snake_case : Dict = weights_name.replace('''.bin''' , f"""-{idx+1:05d}-of-{len(_snake_case ):05d}.bin""" ) __snake_case : List[Any] = os.path.join(_snake_case , weights_name.replace('''.bin''' , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(_snake_case , os.path.join(_snake_case , _snake_case ) ) for key in shard: __snake_case : List[str] = shard_file # Add the metadata __snake_case : Dict = {'''total_size''': total_size} __snake_case : Dict = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(_snake_case , _snake_case ) , '''w''' , encoding='''utf-8''' ) as f: __snake_case : Optional[Any] = json.dumps(_snake_case , indent=2 , sort_keys=_snake_case ) + '''\n''' f.write(_snake_case ) return metadata, index if __name__ == "__main__": SCREAMING_SNAKE_CASE : Any = 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.""", ) SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) SCREAMING_SNAKE_CASE : Any = 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) SCREAMING_SNAKE_CASE : Dict = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("""Done""") model.save_pretrained(args.pytorch_dump_folder_path)
102
'''simple docstring''' from collections.abc import Sequence def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: return sum(c * (x**i) for i, c in enumerate(UpperCamelCase ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: lowerCamelCase__ : str = 0.0 for coeff in reversed(UpperCamelCase ): lowerCamelCase__ : Optional[int] = result * x + coeff return result if __name__ == "__main__": _A : Any =(0.0, 0.0, 5.0, 9.3, 7.0) _A : Optional[Any] =10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
41
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _a = logging.get_logger(__name__) _a = { """microsoft/swin-tiny-patch4-window7-224""": ( """https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json""" ), # See all Swin models at https://huggingface.co/models?filter=swin } class _UpperCAmelCase( lowerCamelCase , lowerCamelCase ): lowercase__ = 'swin' lowercase__ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , __a=2_24 , __a=4 , __a=3 , __a=96 , __a=[2, 2, 6, 2] , __a=[3, 6, 12, 24] , __a=7 , __a=4.0 , __a=True , __a=0.0 , __a=0.0 , __a=0.1 , __a="gelu" , __a=False , __a=0.02 , __a=1e-5 , __a=32 , __a=None , __a=None , **__a , ) -> List[str]: '''simple docstring''' super().__init__(**__a) _UpperCamelCase = image_size _UpperCamelCase = patch_size _UpperCamelCase = num_channels _UpperCamelCase = embed_dim _UpperCamelCase = depths _UpperCamelCase = len(__a) _UpperCamelCase = num_heads _UpperCamelCase = window_size _UpperCamelCase = mlp_ratio _UpperCamelCase = qkv_bias _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = drop_path_rate _UpperCamelCase = hidden_act _UpperCamelCase = use_absolute_embeddings _UpperCamelCase = layer_norm_eps _UpperCamelCase = initializer_range _UpperCamelCase = encoder_stride # 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 _UpperCamelCase = int(embed_dim * 2 ** (len(__a) - 1)) _UpperCamelCase = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__a) + 1)] _UpperCamelCase , _UpperCamelCase = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names) class _UpperCAmelCase( lowerCamelCase ): lowercase__ = version.parse('1.11' ) @property def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def UpperCAmelCase ( self) -> float: '''simple docstring''' return 1e-4
100
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _a = logging.get_logger(__name__) _a = { """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""", # See all DETR models at https://huggingface.co/models?filter=detr } class _UpperCAmelCase( lowerCamelCase ): lowercase__ = 'detr' lowercase__ = ['past_key_values'] lowercase__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , __a=True , __a=None , __a=3 , __a=1_00 , __a=6 , __a=20_48 , __a=8 , __a=6 , __a=20_48 , __a=8 , __a=0.0 , __a=0.0 , __a=True , __a="relu" , __a=2_56 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.02 , __a=1.0 , __a=False , __a="sine" , __a="resnet50" , __a=True , __a=False , __a=1 , __a=5 , __a=2 , __a=1 , __a=1 , __a=5 , __a=2 , __a=0.1 , **__a , ) -> Tuple: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''') if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''') _UpperCamelCase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']) elif isinstance(__a , __a): _UpperCamelCase = backbone_config.get('''model_type''') _UpperCamelCase = CONFIG_MAPPING[backbone_model_type] _UpperCamelCase = config_class.from_dict(__a) # set timm attributes to None _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None, None, None _UpperCamelCase = use_timm_backbone _UpperCamelCase = backbone_config _UpperCamelCase = num_channels _UpperCamelCase = num_queries _UpperCamelCase = d_model _UpperCamelCase = encoder_ffn_dim _UpperCamelCase = encoder_layers _UpperCamelCase = encoder_attention_heads _UpperCamelCase = decoder_ffn_dim _UpperCamelCase = decoder_layers _UpperCamelCase = decoder_attention_heads _UpperCamelCase = dropout _UpperCamelCase = attention_dropout _UpperCamelCase = activation_dropout _UpperCamelCase = activation_function _UpperCamelCase = init_std _UpperCamelCase = init_xavier_std _UpperCamelCase = encoder_layerdrop _UpperCamelCase = decoder_layerdrop _UpperCamelCase = encoder_layers _UpperCamelCase = auxiliary_loss _UpperCamelCase = position_embedding_type _UpperCamelCase = backbone _UpperCamelCase = use_pretrained_backbone _UpperCamelCase = dilation # Hungarian matcher _UpperCamelCase = class_cost _UpperCamelCase = bbox_cost _UpperCamelCase = giou_cost # Loss coefficients _UpperCamelCase = mask_loss_coefficient _UpperCamelCase = dice_loss_coefficient _UpperCamelCase = bbox_loss_coefficient _UpperCamelCase = giou_loss_coefficient _UpperCamelCase = eos_coefficient super().__init__(is_encoder_decoder=__a , **__a) @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return self.encoder_attention_heads @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return self.d_model @classmethod def UpperCAmelCase ( cls , __a , **__a) -> Any: '''simple docstring''' return cls(backbone_config=__a , **__a) def UpperCAmelCase ( self) -> Dict[str, any]: '''simple docstring''' _UpperCamelCase = copy.deepcopy(self.__dict__) if output["backbone_config"] is not None: _UpperCamelCase = self.backbone_config.to_dict() _UpperCamelCase = self.__class__.model_type return output class _UpperCAmelCase( lowerCamelCase ): lowercase__ = version.parse('1.11' ) @property def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ]) @property def UpperCAmelCase ( self) -> float: '''simple docstring''' return 1e-5 @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return 12
100
1
"""simple docstring""" from __future__ import annotations import requests A = set( '''approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'''.split() ) def __A ( a_ :str , a_ :int = 1 , a_ :str = "new" , a_ :list | None = None) -> dict: __a : List[Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(__A) - valid_terms)): __a : List[Any] = F"""Invalid search term: {invalid_search_terms}""" raise ValueError(__A) __a : Dict = requests.get( F"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 4_29: raise requests.HTTPError __a : Dict = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(__A)} __a : List[Any] = {} for id_ in range(__A): __a : Any = { item: data['data']['children'][id_]['data'][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('''learnpython''', wanted_data=['''title''', '''url''', '''selftext''']))
160
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase , unittest.TestCase ): # TODO: is there an appropriate internal test set? A : List[str] = "ssube/stable-diffusion-x4-upscaler-onnx" def lowerCAmelCase__ ( self : int , _lowerCAmelCase : List[Any]=0 ): __snake_case : int = floats_tensor((1, 3, 1_28, 1_28) , rng=random.Random(_lowerCAmelCase ) ) __snake_case : Any = torch.manual_seed(_lowerCAmelCase ) __snake_case : str = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowerCAmelCase__ ( self : Any ): __snake_case : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : Dict = self.get_dummy_inputs() __snake_case : int = pipe(**_lowerCAmelCase ).images __snake_case : List[Any] = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_12, 5_12, 3) __snake_case : List[str] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def lowerCAmelCase__ ( self : Optional[int] ): __snake_case : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __snake_case : Any = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : Any = self.get_dummy_inputs() __snake_case : Optional[Any] = pipe(**_lowerCAmelCase ).images __snake_case : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __snake_case : Optional[int] = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCAmelCase__ ( self : List[Any] ): __snake_case : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __snake_case : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : int = self.get_dummy_inputs() __snake_case : List[str] = pipe(**_lowerCAmelCase ).images __snake_case : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __snake_case : Optional[int] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCAmelCase__ ( self : List[str] ): __snake_case : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __snake_case : Tuple = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : int = self.get_dummy_inputs() __snake_case : List[str] = pipe(**_lowerCAmelCase ).images __snake_case : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __snake_case : Union[str, Any] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowerCAmelCase__ ( self : List[str] ): __snake_case : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __snake_case : Dict = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : List[str] = self.get_dummy_inputs() __snake_case : List[str] = pipe(**_lowerCAmelCase ).images __snake_case : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __snake_case : Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def lowerCAmelCase__ ( self : Tuple ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase__ ( self : Any ): __snake_case : List[Any] = ort.SessionOptions() __snake_case : Dict = False return options def lowerCAmelCase__ ( self : List[Any] ): __snake_case : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __snake_case : List[str] = init_image.resize((1_28, 1_28) ) # using the PNDM scheduler by default __snake_case : Any = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : Union[str, Any] = """A fantasy landscape, trending on artstation""" __snake_case : Union[str, Any] = torch.manual_seed(0 ) __snake_case : Dict = pipe( prompt=_lowerCAmelCase , image=_lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=10 , generator=_lowerCAmelCase , output_type="""np""" , ) __snake_case : Union[str, Any] = output.images __snake_case : Union[str, Any] = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 5_12, 3) __snake_case : int = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def lowerCAmelCase__ ( self : Tuple ): __snake_case : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __snake_case : Union[str, Any] = init_image.resize((1_28, 1_28) ) __snake_case : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , subfolder="""scheduler""" ) __snake_case : Any = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , scheduler=_lowerCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __snake_case : List[Any] = """A fantasy landscape, trending on artstation""" __snake_case : int = torch.manual_seed(0 ) __snake_case : List[Any] = pipe( prompt=_lowerCAmelCase , image=_lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=20 , generator=_lowerCAmelCase , output_type="""np""" , ) __snake_case : Any = output.images __snake_case : List[Any] = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 5_12, 3) __snake_case : Optional[Any] = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
363
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def snake_case__ ( self : Any ): __snake_case : Dict = """| <pad> <unk> <s> </s> a b c d e f g h i j k""".split() __snake_case : str = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) __snake_case : List[str] = { """unk_token""": """<unk>""", """bos_token""": """<s>""", """eos_token""": """</s>""", } __snake_case : str = { """feature_size""": 1, """padding_value""": 0.0, """sampling_rate""": 1_60_00, """return_attention_mask""": False, """do_normalize""": True, } __snake_case : Optional[Any] = tempfile.mkdtemp() __snake_case : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __snake_case : Any = os.path.join(self.tmpdirname , _lowerCAmelCase ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowerCAmelCase ) + """\n""" ) with open(self.feature_extraction_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowerCAmelCase ) + """\n""" ) # load decoder from hub __snake_case : Optional[int] = """hf-internal-testing/ngram-beam-search-decoder""" def snake_case__ ( self : Optional[Any] , **_lowerCAmelCase : Tuple ): __snake_case : int = self.add_kwargs_tokens_map.copy() kwargs.update(_lowerCAmelCase ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def snake_case__ ( self : Union[str, Any] , **_lowerCAmelCase : Optional[int] ): return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def snake_case__ ( self : Dict , **_lowerCAmelCase : Tuple ): return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **_lowerCAmelCase ) def snake_case__ ( self : List[str] ): shutil.rmtree(self.tmpdirname ) def snake_case__ ( self : Union[str, Any] ): __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Tuple = self.get_feature_extractor() __snake_case : Dict = self.get_decoder() __snake_case : List[str] = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCAmelCase ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCAmelCase ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , _lowerCAmelCase ) def snake_case__ ( self : Tuple ): __snake_case : Tuple = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match __snake_case : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def snake_case__ ( self : int ): __snake_case : Tuple = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["""xx"""] ) with self.assertRaisesRegex(_lowerCAmelCase , """include""" ): WavaVecaProcessorWithLM( tokenizer=_lowerCAmelCase , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def snake_case__ ( self : Dict ): __snake_case : int = self.get_feature_extractor() __snake_case : str = self.get_tokenizer() __snake_case : Dict = self.get_decoder() __snake_case : Any = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : List[Any] = floats_list((3, 10_00) ) __snake_case : Optional[Any] = feature_extractor(_lowerCAmelCase , return_tensors="""np""" ) __snake_case : Tuple = processor(_lowerCAmelCase , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case__ ( self : Optional[int] ): __snake_case : Any = self.get_feature_extractor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = self.get_decoder() __snake_case : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : Optional[int] = """This is a test string""" __snake_case : Union[str, Any] = processor(text=_lowerCAmelCase ) __snake_case : Dict = tokenizer(_lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case__ ( self : List[str] , _lowerCAmelCase : List[Any]=(2, 10, 16) , _lowerCAmelCase : str=77 ): np.random.seed(_lowerCAmelCase ) return np.random.rand(*_lowerCAmelCase ) def snake_case__ ( self : Tuple ): __snake_case : List[str] = self.get_feature_extractor() __snake_case : List[str] = self.get_tokenizer() __snake_case : List[str] = self.get_decoder() __snake_case : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : Optional[int] = self._get_dummy_logits(shape=(10, 16) , seed=13 ) __snake_case : int = processor.decode(_lowerCAmelCase ) __snake_case : Optional[int] = decoder.decode_beams(_lowerCAmelCase )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("""</s> <s> </s>""" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["""fork"""], ["""spawn"""]] ) def snake_case__ ( self : List[str] , _lowerCAmelCase : List[str] ): __snake_case : int = self.get_feature_extractor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = self.get_decoder() __snake_case : Dict = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : int = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: __snake_case : Tuple = processor.batch_decode(_lowerCAmelCase ) else: with get_context(_lowerCAmelCase ).Pool() as pool: __snake_case : int = processor.batch_decode(_lowerCAmelCase , _lowerCAmelCase ) __snake_case : int = list(_lowerCAmelCase ) with get_context("""fork""" ).Pool() as p: __snake_case : Tuple = decoder.decode_beams_batch(_lowerCAmelCase , _lowerCAmelCase ) __snake_case , __snake_case , __snake_case : List[Any] = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(_lowerCAmelCase , decoded_processor.text ) self.assertListEqual(["""<s> <s> </s>""", """<s> <s> <s>"""] , decoded_processor.text ) self.assertListEqual(_lowerCAmelCase , decoded_processor.logit_score ) self.assertListEqual(_lowerCAmelCase , decoded_processor.lm_score ) def snake_case__ ( self : Optional[int] ): __snake_case : Optional[Any] = self.get_feature_extractor() __snake_case : int = self.get_tokenizer() __snake_case : str = self.get_decoder() __snake_case : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : int = self._get_dummy_logits() __snake_case : List[str] = 15 __snake_case : Optional[Any] = -20.0 __snake_case : Tuple = -4.0 __snake_case : List[Any] = processor.batch_decode( _lowerCAmelCase , beam_width=_lowerCAmelCase , beam_prune_logp=_lowerCAmelCase , token_min_logp=_lowerCAmelCase , ) __snake_case : List[str] = decoded_processor_out.text __snake_case : str = list(_lowerCAmelCase ) with get_context("""fork""" ).Pool() as pool: __snake_case : Dict = decoder.decode_beams_batch( _lowerCAmelCase , _lowerCAmelCase , beam_width=_lowerCAmelCase , beam_prune_logp=_lowerCAmelCase , token_min_logp=_lowerCAmelCase , ) __snake_case : int = [d[0][0] for d in decoded_decoder_out] __snake_case : List[Any] = [d[0][2] for d in decoded_decoder_out] __snake_case : List[Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(["""</s> <s> <s>""", """<s> <s> <s>"""] , _lowerCAmelCase ) self.assertTrue(np.array_equal(_lowerCAmelCase , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , _lowerCAmelCase , atol=1e-3 ) ) self.assertTrue(np.array_equal(_lowerCAmelCase , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9474] , _lowerCAmelCase , atol=1e-3 ) ) def snake_case__ ( self : Any ): __snake_case : List[Any] = self.get_feature_extractor() __snake_case : Any = self.get_tokenizer() __snake_case : Union[str, Any] = self.get_decoder() __snake_case : Dict = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) __snake_case : Any = self._get_dummy_logits() __snake_case : Any = 2.0 __snake_case : int = 5.0 __snake_case : Optional[int] = -20.0 __snake_case : Optional[int] = True __snake_case : Any = processor.batch_decode( _lowerCAmelCase , alpha=_lowerCAmelCase , beta=_lowerCAmelCase , unk_score_offset=_lowerCAmelCase , lm_score_boundary=_lowerCAmelCase , ) __snake_case : str = decoded_processor_out.text __snake_case : int = list(_lowerCAmelCase ) decoder.reset_params( alpha=_lowerCAmelCase , beta=_lowerCAmelCase , unk_score_offset=_lowerCAmelCase , lm_score_boundary=_lowerCAmelCase , ) with get_context("""fork""" ).Pool() as pool: __snake_case : Tuple = decoder.decode_beams_batch( _lowerCAmelCase , _lowerCAmelCase , ) __snake_case : int = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(["""<s> </s> <s> </s> </s>""", """</s> </s> <s> </s> </s>"""] , _lowerCAmelCase ) __snake_case : List[str] = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , _lowerCAmelCase ) def snake_case__ ( self : Dict ): __snake_case : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) __snake_case : Union[str, Any] = processor.decoder.model_container[processor.decoder._model_key] __snake_case : Optional[int] = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() __snake_case : Union[str, Any] = os.listdir(_lowerCAmelCase ) __snake_case : List[str] = ["""alphabet.json""", """language_model"""] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Optional[Any] ): __snake_case : Union[str, Any] = snapshot_download("""hf-internal-testing/processor_with_lm""" ) __snake_case : Dict = WavaVecaProcessorWithLM.from_pretrained(_lowerCAmelCase ) __snake_case : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key] __snake_case : Optional[int] = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() __snake_case : List[str] = os.listdir(_lowerCAmelCase ) __snake_case : List[Any] = os.listdir(_lowerCAmelCase ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Optional[Any] ): __snake_case : Optional[int] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) __snake_case : str = AutoProcessor.from_pretrained("""hf-internal-testing/processor_with_lm""" ) __snake_case : Optional[int] = floats_list((3, 10_00) ) __snake_case : Union[str, Any] = processor_wavaveca(_lowerCAmelCase , return_tensors="""np""" ) __snake_case : Union[str, Any] = processor_auto(_lowerCAmelCase , return_tensors="""np""" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 ) __snake_case : Dict = self._get_dummy_logits() __snake_case : List[Any] = processor_wavaveca.batch_decode(_lowerCAmelCase ) __snake_case : List[Any] = processor_auto.batch_decode(_lowerCAmelCase ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def snake_case__ ( self : str ): __snake_case : int = self.get_feature_extractor() __snake_case : List[str] = self.get_tokenizer() __snake_case : Optional[Any] = self.get_decoder() __snake_case : Union[str, Any] = WavaVecaProcessorWithLM(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , decoder=_lowerCAmelCase ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , ) @staticmethod def snake_case__ ( _lowerCAmelCase : Any , _lowerCAmelCase : Tuple ): __snake_case : Union[str, Any] = [d[key] for d in offsets] return retrieved_list def snake_case__ ( self : Dict ): __snake_case : int = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) __snake_case : List[str] = self._get_dummy_logits()[0] __snake_case : str = processor.decode(_lowerCAmelCase , output_word_offsets=_lowerCAmelCase ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(_lowerCAmelCase , _lowerCAmelCase ) ) self.assertEqual(""" """.join(self.get_from_offsets(outputs["""word_offsets"""] , """word""" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """word""" ) , ["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """start_offset""" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] , """end_offset""" ) , [1, 3, 5] ) def snake_case__ ( self : List[str] ): __snake_case : Any = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) __snake_case : Optional[int] = self._get_dummy_logits() __snake_case : int = processor.batch_decode(_lowerCAmelCase , output_word_offsets=_lowerCAmelCase ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(_lowerCAmelCase , _lowerCAmelCase ) ) self.assertListEqual( [""" """.join(self.get_from_offsets(_lowerCAmelCase , """word""" ) ) for o in outputs["""word_offsets"""]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """word""" ) , ["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """start_offset""" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] , """end_offset""" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def snake_case__ ( self : Optional[Any] ): import torch __snake_case : Optional[Any] = load_dataset("""common_voice""" , """en""" , split="""train""" , streaming=_lowerCAmelCase ) __snake_case : Any = ds.cast_column("""audio""" , datasets.Audio(sampling_rate=1_60_00 ) ) __snake_case : List[Any] = iter(_lowerCAmelCase ) __snake_case : Optional[int] = next(_lowerCAmelCase ) __snake_case : str = AutoProcessor.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) __snake_case : str = WavaVecaForCTC.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train __snake_case : List[str] = processor(sample["""audio"""]["""array"""] , return_tensors="""pt""" ).input_values with torch.no_grad(): __snake_case : Dict = model(_lowerCAmelCase ).logits.cpu().numpy() __snake_case : Any = processor.decode(logits[0] , output_word_offsets=_lowerCAmelCase ) __snake_case : Optional[Any] = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate __snake_case : Dict = [ { """start_time""": d["""start_offset"""] * time_offset, """end_time""": d["""end_offset"""] * time_offset, """word""": d["""word"""], } for d in output["""word_offsets"""] ] __snake_case : Dict = """WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL""" # output words self.assertEqual(""" """.join(self.get_from_offsets(_lowerCAmelCase , """word""" ) ) , _lowerCAmelCase ) self.assertEqual(""" """.join(self.get_from_offsets(_lowerCAmelCase , """word""" ) ) , output.text ) # output times __snake_case : Dict = torch.tensor(self.get_from_offsets(_lowerCAmelCase , """start_time""" ) ) __snake_case : Optional[Any] = torch.tensor(self.get_from_offsets(_lowerCAmelCase , """end_time""" ) ) # fmt: off __snake_case : Optional[Any] = torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599] ) __snake_case : Optional[int] = torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=0.01 ) ) self.assertTrue(torch.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=0.01 ) )
20
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, 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 a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class a_ ( _lowerCAmelCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ["pixel_values"] def __init__( self , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BICUBIC , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = 1 / 255 , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = True , **_lowerCamelCase , ) ->None: super().__init__(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = size if size is not None else {"shortest_edge": 224} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE : Any = do_resize SCREAMING_SNAKE_CASE : List[str] = size SCREAMING_SNAKE_CASE : str = resample SCREAMING_SNAKE_CASE : Optional[Any] = do_center_crop SCREAMING_SNAKE_CASE : Union[str, Any] = crop_size SCREAMING_SNAKE_CASE : Optional[int] = do_rescale SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD SCREAMING_SNAKE_CASE : List[str] = do_convert_rgb def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BICUBIC , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: SCREAMING_SNAKE_CASE : Optional[Any] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = get_resize_output_image_size(_lowerCamelCase , size=size['''shortest_edge'''] , default_to_square=_lowerCamelCase ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(_lowerCamelCase , size=(size['''height'''], size['''width''']) , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase , ) ->int: return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ) ->PIL.Image.Image: SCREAMING_SNAKE_CASE : int = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Any = size if size is not None else self.size SCREAMING_SNAKE_CASE : Dict = get_size_dict(_lowerCamelCase , param_name='''size''' , default_to_square=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Any = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : Optional[Any] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : int = get_size_dict(_lowerCamelCase , param_name='''crop_size''' , default_to_square=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[int] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE : Any = 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: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE : Optional[int] = [convert_to_rgb(_lowerCamelCase ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE : int = [self.center_crop(image=_lowerCamelCase , size=_lowerCamelCase ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : int = [self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : int = [self.normalize(image=_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase ) for image in images] SCREAMING_SNAKE_CASE : Any = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
313
from __future__ import annotations _snake_case : Any = "Muhammad Umer Farooq" _snake_case : Optional[int] = "MIT" _snake_case : Union[str, Any] = "1.0.0" _snake_case : Optional[Any] = "Muhammad Umer Farooq" _snake_case : List[Any] = "contact@muhammadumerfarooq.me" _snake_case : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : str ) -> None: super().__init__() __snake_case : list[str] = [] __snake_case : Any = domain def __snake_case ( self : List[str] , lowerCamelCase : str , lowerCamelCase : list[tuple[str, str | None]] ) -> None: # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Any = parse.urljoin(self.domain , lowerCamelCase ) self.urls.append(lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): return ".".join(get_sub_domain_name(__lowerCamelCase ).split("." )[-2:] ) def lowerCAmelCase_ ( __lowerCamelCase ): return parse.urlparse(__lowerCamelCase ).netloc def lowerCAmelCase_ ( __lowerCamelCase = "https://github.com" ): __snake_case : Tuple = get_domain_name(__lowerCamelCase ) # Initialize the parser __snake_case : Dict = Parser(__lowerCamelCase ) try: # Open URL __snake_case : Any = requests.get(__lowerCamelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[str] = requests.get(__lowerCamelCase ) # Get the valid email. __snake_case : Any = re.findall("[a-zA-Z0-9]+@" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__lowerCamelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__lowerCamelCase ) if __name__ == "__main__": _snake_case : Union[str, Any] = emails_from_url("https://github.com") print(f'''{len(emails)} emails found:''') print("\n".join(sorted(emails)))
123
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod @abstractmethod def a_ ( __lowerCAmelCase : ArgumentParser ) -> List[Any]: """simple docstring""" raise NotImplementedError() @abstractmethod def a_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" raise NotImplementedError()
358
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class A : '''simple docstring''' __lowerCamelCase : Optional[Any] = BlenderbotSmallConfig __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : List[Any] = '''gelu''' def __init__( self : Dict , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str]=13 , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : Union[str, Any]=99 , __lowerCAmelCase : Union[str, Any]=32 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : Optional[Any]=4 , __lowerCAmelCase : Tuple=37 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : List[str]=20 , __lowerCAmelCase : Union[str, Any]=2 , __lowerCAmelCase : Dict=1 , __lowerCAmelCase : int=0 , ) -> Any: """simple docstring""" A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def a_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = 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 , ) A__ = prepare_blenderbot_small_inputs_dict(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return config, inputs_dict def a_ ( self : Union[str, Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] ) -> str: """simple docstring""" A__ = TFBlenderbotSmallModel(config=__lowerCAmelCase ).get_decoder() A__ = inputs_dict["""input_ids"""] A__ = input_ids[:1, :] A__ = inputs_dict["""attention_mask"""][:1, :] A__ = inputs_dict["""head_mask"""] A__ = 1 # first forward pass A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , head_mask=__lowerCAmelCase , use_cache=__lowerCAmelCase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] A__ = 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 A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCAmelCase , __lowerCAmelCase , rtol=1e-3 ) def __lowerCamelCase ( __a :Dict , __a :Tuple , __a :List[Any] , __a :List[str]=None , __a :List[Any]=None , __a :Optional[Any]=None , __a :List[str]=None , __a :int=None , ) -> Optional[Any]: """simple docstring""" if attention_mask is None: A__ = tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = 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 A (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Tuple = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase : List[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase : Tuple = ( { '''conversational''': TFBlenderbotSmallForConditionalGeneration, '''feature-extraction''': TFBlenderbotSmallModel, '''summarization''': TFBlenderbotSmallForConditionalGeneration, '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration, '''translation''': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase : Dict = True __lowerCamelCase : Optional[Any] = False __lowerCamelCase : Tuple = False def a_ ( self : Tuple ) -> Optional[int]: """simple docstring""" A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=__lowerCAmelCase ) def a_ ( self : List[str] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def a_ ( self : List[str] ) -> Any: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCAmelCase ) @require_tokenizers @require_tf class A (unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = [ '''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ''' ''' i\'m going to throw up.\nand why is that?''' ] __lowerCamelCase : Optional[int] = '''facebook/blenderbot_small-90M''' @cached_property def a_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def a_ ( self : List[str] ) -> List[str]: """simple docstring""" A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def a_ ( self : int ) -> Optional[Any]: """simple docstring""" A__ = self.tokenizer(self.src_text , return_tensors="""tf""" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCAmelCase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
276
0
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class lowerCamelCase__ ( unittest.TestCase ): """simple docstring""" __a = MODEL_FOR_MASKED_LM_MAPPING __a = TF_MODEL_FOR_MASKED_LM_MAPPING def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' __UpperCAmelCase : List[str] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" ) __UpperCAmelCase : List[str] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ {"""sequence""": """My name is grouped""", """score""": 2.1e-0_5, """token""": 38_015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1e-0_5, """token""": 25_506, """token_str""": """ accuser"""}, ] , ) __UpperCAmelCase : Dict = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1e-0_5, """token""": 38_015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1e-0_5, """token""": 25_506, """token_str""": """ accuser""", }, ] , ) __UpperCAmelCase : Optional[Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ {"""sequence""": """My name is Clara""", """score""": 2e-0_5, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2e-0_5, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9e-0_5, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" ) __UpperCAmelCase : List[Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ {"""sequence""": """My name is Maul""", """score""": 2.2e-0_5, """token""": 35_676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2e-0_5, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : Any = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2e-0_5, """token""": 35_676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2e-0_5, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1e-0_5, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2e-0_5, """token""": 2_941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2e-0_5, """token""": 13_606, """token_str""": """ Clara"""}, ] , ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask> <mask>""" , top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=6 ) , [ [ { """score""": 2.2e-0_5, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2e-0_5, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2e-0_5, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2e-0_5, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def lowerCamelCase__ ( self : int ): '''simple docstring''' __UpperCAmelCase : List[Any] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" ) # convert model to fp16 pipe.model.half() __UpperCAmelCase : List[str] = pipe("""Paris is the [MASK] of France.""" ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(UpperCamelCase , UpperCamelCase ) @slow @require_torch def lowerCamelCase__ ( self : Any ): '''simple docstring''' __UpperCAmelCase : List[str] = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" ) self.run_large_test(UpperCamelCase ) @slow @require_tf def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' __UpperCAmelCase : Optional[int] = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" ) self.run_large_test(UpperCamelCase ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' __UpperCAmelCase : str = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase ) , [ {"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1_573, """token_str""": """ Chris"""}, ] , ) __UpperCAmelCase : Tuple = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase ) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.251, """token""": 2_201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.214, """token""": 12_790, """token_str""": """ Lyon""", }, ] , ) __UpperCAmelCase : int = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase ) , [ {"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' __UpperCAmelCase : Tuple = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Tuple = None self.run_pipeline_test(UpperCamelCase , [] ) @require_tf def lowerCamelCase__ ( self : int ): '''simple docstring''' __UpperCAmelCase : Any = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" ) __UpperCAmelCase : List[str] = None __UpperCAmelCase : Union[str, Any] = None self.run_pipeline_test(UpperCamelCase , [] ) def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase : int , UpperCamelCase : Tuple , UpperCamelCase : str ): '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" ) __UpperCAmelCase : Union[str, Any] = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) __UpperCAmelCase : Tuple = [ f'''This is another {tokenizer.mask_token} test''', ] return fill_masker, examples def lowerCamelCase__ ( self : int , UpperCamelCase : Tuple , UpperCamelCase : Union[str, Any] ): '''simple docstring''' __UpperCAmelCase : List[str] = fill_masker.tokenizer __UpperCAmelCase : Union[str, Any] = fill_masker.model __UpperCAmelCase : Dict = fill_masker( f'''This is a {tokenizer.mask_token}''' , ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) __UpperCAmelCase : Optional[Any] = fill_masker([f'''This is a {tokenizer.mask_token}'''] ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) __UpperCAmelCase : Union[str, Any] = fill_masker([f'''This is a {tokenizer.mask_token}''', f'''Another {tokenizer.mask_token} great test.'''] ) self.assertEqual( UpperCamelCase , [ [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ], [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ], ] , ) with self.assertRaises(UpperCamelCase ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(UpperCamelCase ): fill_masker("""This is""" ) self.run_test_top_k(UpperCamelCase , UpperCamelCase ) self.run_test_targets(UpperCamelCase , UpperCamelCase ) self.run_test_top_k_targets(UpperCamelCase , UpperCamelCase ) self.fill_mask_with_duplicate_targets_and_top_k(UpperCamelCase , UpperCamelCase ) self.fill_mask_with_multiple_masks(UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : str , UpperCamelCase : Any , UpperCamelCase : Optional[int] ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = tokenizer.get_vocab() __UpperCAmelCase : str = sorted(vocab.keys() )[:2] # Pipeline argument __UpperCAmelCase : Any = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase , targets=UpperCamelCase ) __UpperCAmelCase : Any = fill_masker(f'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) __UpperCAmelCase : Optional[Any] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , UpperCamelCase ) __UpperCAmelCase : Optional[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(UpperCamelCase ) ) # Call argument __UpperCAmelCase : Optional[Any] = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) __UpperCAmelCase : Optional[Any] = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) __UpperCAmelCase : List[Any] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , UpperCamelCase ) __UpperCAmelCase : Any = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(UpperCamelCase ) ) # Score equivalence __UpperCAmelCase : Any = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase ) __UpperCAmelCase : List[Any] = [top_mask["""token_str"""] for top_mask in outputs] __UpperCAmelCase : str = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase ) == set(UpperCamelCase ): __UpperCAmelCase : List[str] = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase ) __UpperCAmelCase : Tuple = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(UpperCamelCase ) , nested_simplify(UpperCamelCase ) ) # Raises with invalid with self.assertRaises(UpperCamelCase ): __UpperCAmelCase : Optional[Any] = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(UpperCamelCase ): __UpperCAmelCase : Optional[Any] = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets=[""""""] ) with self.assertRaises(UpperCamelCase ): __UpperCAmelCase : str = fill_masker(f'''This is a {tokenizer.mask_token}''' , targets="""""" ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : int ): '''simple docstring''' __UpperCAmelCase : str = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase , top_k=2 ) __UpperCAmelCase : int = fill_masker(f'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) __UpperCAmelCase : Any = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) __UpperCAmelCase : List[Any] = fill_masker(f'''This is a {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase , [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ] , ) self.assertEqual(nested_simplify(UpperCamelCase ) , nested_simplify(UpperCamelCase ) ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' __UpperCAmelCase : Optional[int] = tokenizer.get_vocab() __UpperCAmelCase : Optional[Any] = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) # top_k=2, ntargets=3 __UpperCAmelCase : Union[str, Any] = sorted(vocab.keys() )[:3] __UpperCAmelCase : int = fill_masker(f'''This is a {tokenizer.mask_token}''' , top_k=2 , targets=UpperCamelCase ) # If we use the most probably targets, and filter differently, we should still # have the same results __UpperCAmelCase : str = [el["""token_str"""] for el in sorted(UpperCamelCase , key=lambda UpperCamelCase : x["score"] , reverse=UpperCamelCase )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase ).issubset(UpperCamelCase ): __UpperCAmelCase : Optional[Any] = fill_masker(f'''This is a {tokenizer.mask_token}''' , top_k=3 , targets=UpperCamelCase ) # They should yield exactly the same result self.assertEqual(nested_simplify(UpperCamelCase ) , nested_simplify(UpperCamelCase ) ) def lowerCamelCase__ ( self : str , UpperCamelCase : str , UpperCamelCase : Any ): '''simple docstring''' __UpperCAmelCase : Tuple = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) __UpperCAmelCase : Any = tokenizer.get_vocab() # String duplicates + id duplicates __UpperCAmelCase : Tuple = sorted(vocab.keys() )[:3] __UpperCAmelCase : Tuple = [targets[0], targets[1], targets[0], targets[2], targets[1]] __UpperCAmelCase : int = fill_masker(f'''My name is {tokenizer.mask_token}''' , targets=UpperCamelCase , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(UpperCamelCase ) , 3 ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = FillMaskPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase ) __UpperCAmelCase : List[str] = fill_masker( f'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase , [ [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ], [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ], [ {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, {"""sequence""": ANY(UpperCamelCase ), """score""": ANY(UpperCamelCase ), """token""": ANY(UpperCamelCase ), """token_str""": ANY(UpperCamelCase )}, ], ] , )
115
"""simple docstring""" import math def lowerCamelCase ( _UpperCamelCase : int ) -> list[int]: '''simple docstring''' __UpperCAmelCase : List[Any] = [] __UpperCAmelCase : Dict = 2 __UpperCAmelCase : Union[str, Any] = int(math.sqrt(_UpperCamelCase ) ) # Size of every segment __UpperCAmelCase : Tuple = [True] * (end + 1) __UpperCAmelCase : int = [] while start <= end: if temp[start] is True: in_prime.append(_UpperCamelCase ) for i in range(start * start , end + 1 , _UpperCamelCase ): __UpperCAmelCase : Dict = False start += 1 prime += in_prime __UpperCAmelCase : Optional[int] = end + 1 __UpperCAmelCase : Dict = min(2 * end , _UpperCamelCase ) while low <= n: __UpperCAmelCase : Union[str, Any] = [True] * (high - low + 1) for each in in_prime: __UpperCAmelCase : Dict = math.floor(low / each ) * each if t < low: t += each for j in range(_UpperCamelCase , high + 1 , _UpperCamelCase ): __UpperCAmelCase : Tuple = False for j in range(len(_UpperCamelCase ) ): if temp[j] is True: prime.append(j + low ) __UpperCAmelCase : Tuple = high + 1 __UpperCAmelCase : Optional[int] = min(high + end , _UpperCamelCase ) return prime print(sieve(10**6))
115
1
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class a_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) lowerCAmelCase_ = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler('sample_euler' ) lowerCAmelCase_ = "A painting of a squirrel eating a burger" lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = sd_pipe([prompt] , generator=_a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type='np' ) lowerCAmelCase_ = output.images lowerCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase_ = np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _lowercase ( self ) -> Any: '''simple docstring''' lowerCAmelCase_ = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) lowerCAmelCase_ = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler('sample_euler' ) lowerCAmelCase_ = "A painting of a squirrel eating a burger" lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = sd_pipe([prompt] , generator=_a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type='np' ) lowerCAmelCase_ = output.images lowerCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase_ = np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) lowerCAmelCase_ = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler('sample_dpmpp_2m' ) lowerCAmelCase_ = "A painting of a squirrel eating a burger" lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = sd_pipe( [prompt] , generator=_a , guidance_scale=7.5 , num_inference_steps=1_5 , output_type='np' , use_karras_sigmas=_a , ) lowerCAmelCase_ = output.images lowerCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase_ = np.array( [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
369
from maths.prime_factors import prime_factors def lowerCamelCase ( a_ ) -> int: if not isinstance(a_ , a_ ): lowerCAmelCase_ = F'''Input value of [number={number}] must be an integer''' raise TypeError(a_ ) if number < 1: raise ValueError('Input must be a positive integer' ) return -1 if len(prime_factors(a_ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
14
0
"""simple docstring""" from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch lowerCAmelCase__ = logging.get_logger(__name__) @add_end_docstrings( _lowercase , R"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class _lowerCamelCase ( _lowercase ): def snake_case_ (self , __a ) -> np.ndarray: if self.framework == "tf": UpperCamelCase = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": UpperCamelCase = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__a ) else: raise ValueError("Unsupported framework" ) return masked_index def snake_case_ (self , __a ) -> np.ndarray: UpperCamelCase = self.get_masked_index(__a ) UpperCamelCase = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , F"No mask_token ({self.tokenizer.mask_token}) found on the input" , ) def snake_case_ (self , __a ) -> Any: if isinstance(__a , __a ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(__a ) def snake_case_ (self , __a , __a=None , **__a ) -> Dict[str, GenericTensor]: if return_tensors is None: UpperCamelCase = self.framework UpperCamelCase = self.tokenizer(__a , return_tensors=__a ) self.ensure_exactly_one_mask_token(__a ) return model_inputs def snake_case_ (self , __a ) -> Dict: UpperCamelCase = self.model(**__a ) UpperCamelCase = model_inputs["input_ids"] return model_outputs def snake_case_ (self , __a , __a=5 , __a=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: UpperCamelCase = target_ids.shape[0] UpperCamelCase = model_outputs["input_ids"][0] UpperCamelCase = model_outputs["logits"] if self.framework == "tf": UpperCamelCase = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] UpperCamelCase = outputs.numpy() UpperCamelCase = outputs[0, masked_index, :] UpperCamelCase = stable_softmax(__a , axis=-1 ) if target_ids is not None: UpperCamelCase = tf.gather_nd(tf.squeeze(__a , 0 ) , target_ids.reshape(-1 , 1 ) ) UpperCamelCase = tf.expand_dims(__a , 0 ) UpperCamelCase = tf.math.top_k(__a , k=__a ) UpperCamelCase , UpperCamelCase = topk.values.numpy(), topk.indices.numpy() else: UpperCamelCase = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__a ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample UpperCamelCase = outputs[0, masked_index, :] UpperCamelCase = logits.softmax(dim=-1 ) if target_ids is not None: UpperCamelCase = probs[..., target_ids] UpperCamelCase , UpperCamelCase = probs.topk(__a ) UpperCamelCase = [] UpperCamelCase = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): UpperCamelCase = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place UpperCamelCase = input_ids.numpy().copy() if target_ids is not None: UpperCamelCase = target_ids[p].tolist() UpperCamelCase = p # Filter padding out: UpperCamelCase = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back UpperCamelCase = self.tokenizer.decode(__a , skip_special_tokens=__a ) UpperCamelCase = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(__a ) result.append(__a ) if single_mask: return result[0] return result def snake_case_ (self , __a , __a=None ) -> Any: if isinstance(__a , __a ): UpperCamelCase = [targets] try: UpperCamelCase = self.tokenizer.get_vocab() except Exception: UpperCamelCase = {} UpperCamelCase = [] for target in targets: UpperCamelCase = vocab.get(__a , __a ) if id_ is None: UpperCamelCase = self.tokenizer( __a , add_special_tokens=__a , return_attention_mask=__a , return_token_type_ids=__a , max_length=1 , truncation=__a , )["input_ids"] if len(__a ) == 0: logger.warning( F"The specified target token `{target}` does not exist in the model vocabulary. " "We cannot replace it with anything meaningful, ignoring it" ) continue UpperCamelCase = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"The specified target token `{target}` does not exist in the model vocabulary. " F"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`." ) target_ids.append(id_ ) UpperCamelCase = list(set(__a ) ) if len(__a ) == 0: raise ValueError("At least one target must be provided when passed." ) UpperCamelCase = np.array(__a ) return target_ids def snake_case_ (self , __a=None , __a=None ) -> int: UpperCamelCase = {} if targets is not None: UpperCamelCase = self.get_target_ids(__a , __a ) UpperCamelCase = target_ids if top_k is not None: UpperCamelCase = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__(self , __a , *__a , **__a ) -> Tuple: UpperCamelCase = super().__call__(__a , **__a ) if isinstance(__a , __a ) and len(__a ) == 1: return outputs[0] return outputs
153
"""simple docstring""" from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split lowerCAmelCase__ = datasets.load_iris() lowerCAmelCase__ = np.array(data['''data''']) lowerCAmelCase__ = np.array(data['''target''']) lowerCAmelCase__ = data['''target_names'''] lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = train_test_split(X, y) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" return np.linalg.norm(np.array(_SCREAMING_SNAKE_CASE ) - np.array(_SCREAMING_SNAKE_CASE ) ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=5 ): """simple docstring""" UpperCamelCase = zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # List of distances of all points from the point to be classified UpperCamelCase = [] for data_point in data: UpperCamelCase = euclidean_distance(data_point[0] , _SCREAMING_SNAKE_CASE ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. UpperCamelCase = [i[1] for i in sorted(_SCREAMING_SNAKE_CASE )[:k]] # Most commonly occurring class among them # is the class into which the point is classified UpperCamelCase = Counter(_SCREAMING_SNAKE_CASE ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
153
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def UpperCAmelCase_ ( self : str ) -> int: torch.manual_seed(0 ) UpperCAmelCase : Tuple = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model def UpperCAmelCase_ ( self : Dict ) -> List[str]: UpperCAmelCase : str = self.dummy_uncond_unet UpperCAmelCase : Optional[int] = KarrasVeScheduler() UpperCAmelCase : str = KarrasVePipeline(unet=__lowercase , scheduler=__lowercase ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) UpperCAmelCase : List[Any] = torch.manual_seed(0 ) UpperCAmelCase : List[Any] = pipe(num_inference_steps=2 , generator=__lowercase , output_type='numpy' ).images UpperCAmelCase : List[str] = torch.manual_seed(0 ) UpperCAmelCase : Any = pipe(num_inference_steps=2 , generator=__lowercase , output_type='numpy' , return_dict=__lowercase )[0] UpperCAmelCase : Dict = image[0, -3:, -3:, -1] UpperCAmelCase : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase : Optional[int] = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: UpperCAmelCase : Any = '''google/ncsnpp-celebahq-256''' UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(__lowercase ) UpperCAmelCase : int = KarrasVeScheduler() UpperCAmelCase : List[str] = KarrasVePipeline(unet=__lowercase , scheduler=__lowercase ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) UpperCAmelCase : Dict = torch.manual_seed(0 ) UpperCAmelCase : List[str] = pipe(num_inference_steps=20 , generator=__lowercase , output_type='numpy' ).images UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCAmelCase : Optional[Any] = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
350
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : str ) -> Tuple: UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) UpperCAmelCase : Dict = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) UpperCAmelCase : Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) UpperCAmelCase : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase : Dict = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase : int = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : str ) -> List[Any]: UpperCAmelCase : Optional[int] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) UpperCAmelCase : Dict = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1' ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) if __name__ == "__main__": lowercase__ = Accelerator() lowercase__ = (accelerator.state.process_index + 2, 10) lowercase__ = torch.randint(0, 10, shape).to(accelerator.device) lowercase__ = "" lowercase__ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase__ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase__ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
280
0
'''simple docstring''' 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) UpperCAmelCase_ : str = logging.getLogger() def snake_case_ ( ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument("""-f""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() return args.f def snake_case_ ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {} _SCREAMING_SNAKE_CASE : List[str] = os.path.join(SCREAMING_SNAKE_CASE__ , """all_results.json""" ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , """r""" ) as f: _SCREAMING_SNAKE_CASE : Any = json.load(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f"""can't find {path}""" ) return results def snake_case_ ( ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.is_available() and torch_device == """cuda""" return is_using_cuda and is_apex_available() UpperCAmelCase_ : List[str] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( _snake_case ): '''simple docstring''' @classmethod def UpperCAmelCase_ ( cls ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU _SCREAMING_SNAKE_CASE : int = tempfile.mkdtemp() _SCREAMING_SNAKE_CASE : List[Any] = os.path.join(cls.tmpdir , """default_config.yml""" ) write_basic_config(save_location=cls.configPath ) _SCREAMING_SNAKE_CASE : Dict = ["""accelerate""", """launch""", """--config_file""", cls.configPath] @classmethod def UpperCAmelCase_ ( cls ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : List[str] = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Dict = get_results(__snake_case ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """glue_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Optional[int] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : Optional[int] = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.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 ) _SCREAMING_SNAKE_CASE : int = get_results(__snake_case ) self.assertLess(result["""perplexity"""] , 100 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """clm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Tuple = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : Any = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Any = get_results(__snake_case ) self.assertLess(result["""perplexity"""] , 42 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """mlm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu _SCREAMING_SNAKE_CASE : List[str] = 7 if get_gpu_count() > 1 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : List[str] = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Optional[Any] = get_results(__snake_case ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertLess(result["""train_loss"""] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """ner_no_trainer""" ) ) ) @unittest.skip(reason="""Fix me @muellerzr""" ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Dict = get_results(__snake_case ) # 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(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """qa_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : Union[str, Any] = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : int = get_results(__snake_case ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """swag_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : str = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : Any = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(__snake_case ) 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(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """summarization_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : Union[str, Any] = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Optional[Any] = get_results(__snake_case ) self.assertGreaterEqual(result["""eval_bleu"""] , 30 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """translation_no_trainer""" ) ) ) @slow def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : str = logging.StreamHandler(sys.stdout ) logger.addHandler(__snake_case ) _SCREAMING_SNAKE_CASE : Any = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : List[Any] = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : int = get_results(__snake_case ) self.assertGreaterEqual(result["""eval_overall_accuracy"""] , 0.10 ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) _SCREAMING_SNAKE_CASE : Tuple = get_results(__snake_case ) # The base model scores a 25% self.assertGreaterEqual(result["""eval_accuracy"""] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """step_1""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__snake_case , """image_classification_no_trainer""" ) ) )
200
'''simple docstring''' def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def snake_case_ ( ): """simple docstring""" assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
200
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {} class snake_case_ ( SCREAMING_SNAKE_CASE_ ): __A : int = "llama" __A : Dict = ["past_key_values"] def __init__( self : Any , lowercase_ : List[str]=3_20_00 , lowercase_ : Union[str, Any]=40_96 , lowercase_ : Optional[Any]=1_10_08 , lowercase_ : Any=32 , lowercase_ : str=32 , lowercase_ : Optional[int]=None , lowercase_ : Dict="silu" , lowercase_ : Dict=20_48 , lowercase_ : List[str]=0.02 , lowercase_ : Union[str, Any]=1E-6 , lowercase_ : Dict=True , lowercase_ : List[str]=0 , lowercase_ : Tuple=1 , lowercase_ : Tuple=2 , lowercase_ : Optional[Any]=1 , lowercase_ : Any=False , lowercase_ : Tuple=None , **lowercase_ : List[Any] , ) -> Optional[int]: lowercase__ : str = vocab_size lowercase__ : List[str] = max_position_embeddings lowercase__ : List[Any] = hidden_size lowercase__ : Union[str, Any] = intermediate_size lowercase__ : Optional[int] = num_hidden_layers lowercase__ : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: lowercase__ : Optional[int] = num_attention_heads lowercase__ : Optional[Any] = num_key_value_heads lowercase__ : int = hidden_act lowercase__ : Any = initializer_range lowercase__ : Any = rms_norm_eps lowercase__ : Union[str, Any] = pretraining_tp lowercase__ : Optional[int] = use_cache lowercase__ : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def __UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " F'''got {self.rope_scaling}''' ) lowercase__ : Optional[Any] = self.rope_scaling.get("type" , __a ) lowercase__ : Tuple = self.rope_scaling.get("factor" , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
350
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node UpperCamelCase = 4 UpperCamelCase = 3 class snake_case_ ( __A ): pass def lowercase_ ( _lowerCamelCase : List[str]): for shard in shards: for i in range(_lowerCamelCase): yield {"i": i, "shard": shard} def lowercase_ ( ): lowercase__ : List[str] = int(os.environ["RANK"]) lowercase__ : Union[str, Any] = int(os.environ["WORLD_SIZE"]) lowercase__ : Union[str, Any] = ArgumentParser() parser.add_argument("--streaming" , type=_lowerCamelCase) parser.add_argument("--local_rank" , type=_lowerCamelCase) parser.add_argument("--num_workers" , type=_lowerCamelCase , default=0) lowercase__ : int = parser.parse_args() lowercase__ : Union[str, Any] = args.streaming lowercase__ : List[Any] = args.num_workers lowercase__ : Dict = {"shards": [f'''shard_{shard_idx}''' for shard_idx in range(_lowerCamelCase)]} lowercase__ : int = IterableDataset.from_generator(_lowerCamelCase , gen_kwargs=_lowerCamelCase) if not streaming: lowercase__ : str = Dataset.from_list(list(_lowerCamelCase)) lowercase__ : List[str] = split_dataset_by_node(_lowerCamelCase , rank=_lowerCamelCase , world_size=_lowerCamelCase) lowercase__ : Any = torch.utils.data.DataLoader(_lowerCamelCase , num_workers=_lowerCamelCase) lowercase__ : Dict = NUM_SHARDS * NUM_ITEMS_PER_SHARD lowercase__ : Any = full_size // world_size expected_local_size += int(rank < (full_size % world_size)) lowercase__ : List[str] = sum(1 for _ in dataloader) if local_size != expected_local_size: raise FailedTestError(f'''local_size {local_size} != expected_local_size {expected_local_size}''') if __name__ == "__main__": main()
333
0
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-base/resolve/main/config.json''', } class __snake_case ( _lowercase): snake_case__ : Dict = "align_text_model" def __init__( self : List[str] , __lowerCAmelCase : Union[str, Any]=3_0_5_2_2 , __lowerCAmelCase : Optional[int]=7_6_8 , __lowerCAmelCase : Dict=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : Optional[Any]=3_0_7_2 , __lowerCAmelCase : str="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : int=0.1 , __lowerCAmelCase : Any=5_1_2 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Any=0.02 , __lowerCAmelCase : List[str]=1E-12 , __lowerCAmelCase : Union[str, Any]=0 , __lowerCAmelCase : Optional[int]="absolute" , __lowerCAmelCase : Optional[Any]=True , **__lowerCAmelCase : Any , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : List[str] = hidden_size _lowerCamelCase : str = num_hidden_layers _lowerCamelCase : Union[str, Any] = num_attention_heads _lowerCamelCase : Dict = hidden_act _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : int = max_position_embeddings _lowerCamelCase : Optional[Any] = type_vocab_size _lowerCamelCase : Any = initializer_range _lowerCamelCase : List[str] = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Union[str, Any] = use_cache _lowerCamelCase : Any = pad_token_id @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , __lowerCAmelCase : Union[str, os.PathLike] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": _lowerCamelCase : int = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__lowerCAmelCase , **__lowerCAmelCase ) class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "align_vision_model" def __init__( self : int , __lowerCAmelCase : int = 3 , __lowerCAmelCase : int = 6_0_0 , __lowerCAmelCase : float = 2.0 , __lowerCAmelCase : float = 3.1 , __lowerCAmelCase : int = 8 , __lowerCAmelCase : List[int] = [3, 3, 5, 3, 5, 5, 3] , __lowerCAmelCase : List[int] = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , __lowerCAmelCase : List[int] = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , __lowerCAmelCase : List[int] = [] , __lowerCAmelCase : List[int] = [1, 2, 2, 2, 1, 2, 1] , __lowerCAmelCase : List[int] = [1, 2, 2, 3, 3, 4, 1] , __lowerCAmelCase : List[int] = [1, 6, 6, 6, 6, 6, 6] , __lowerCAmelCase : float = 0.25 , __lowerCAmelCase : str = "swish" , __lowerCAmelCase : int = 2_5_6_0 , __lowerCAmelCase : str = "mean" , __lowerCAmelCase : float = 0.02 , __lowerCAmelCase : float = 0.0_01 , __lowerCAmelCase : float = 0.99 , __lowerCAmelCase : float = 0.2 , **__lowerCAmelCase : List[str] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : str = image_size _lowerCamelCase : int = width_coefficient _lowerCamelCase : str = depth_coefficient _lowerCamelCase : int = depth_divisor _lowerCamelCase : Union[str, Any] = kernel_sizes _lowerCamelCase : Optional[Any] = in_channels _lowerCamelCase : Optional[Any] = out_channels _lowerCamelCase : List[Any] = depthwise_padding _lowerCamelCase : str = strides _lowerCamelCase : List[str] = num_block_repeats _lowerCamelCase : List[str] = expand_ratios _lowerCamelCase : Any = squeeze_expansion_ratio _lowerCamelCase : Any = hidden_act _lowerCamelCase : List[Any] = hidden_dim _lowerCamelCase : Dict = pooling_type _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = batch_norm_eps _lowerCamelCase : Dict = batch_norm_momentum _lowerCamelCase : List[Any] = drop_connect_rate _lowerCamelCase : int = sum(__lowerCAmelCase ) * 4 @classmethod def SCREAMING_SNAKE_CASE ( cls : str , __lowerCAmelCase : Union[str, os.PathLike] , **__lowerCAmelCase : Tuple ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : Dict = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": _lowerCamelCase : Dict = 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(__lowerCAmelCase , **__lowerCAmelCase ) class __snake_case ( _lowercase): snake_case__ : Tuple = "align" snake_case__ : List[str] = True def __init__( self : Union[str, Any] , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Union[str, Any]=6_4_0 , __lowerCAmelCase : int=1.0 , __lowerCAmelCase : List[str]=0.02 , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) if text_config is None: _lowerCamelCase : Optional[Any] = {} logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''' ) if vision_config is None: _lowerCamelCase : List[str] = {} logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''' ) _lowerCamelCase : List[str] = AlignTextConfig(**__lowerCAmelCase ) _lowerCamelCase : Any = AlignVisionConfig(**__lowerCAmelCase ) _lowerCamelCase : Any = projection_dim _lowerCamelCase : Any = temperature_init_value _lowerCamelCase : Any = initializer_range @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[Any] , __lowerCAmelCase : AlignTextConfig , __lowerCAmelCase : AlignVisionConfig , **__lowerCAmelCase : Optional[int] ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = copy.deepcopy(self.__dict__ ) _lowerCamelCase : List[str] = self.text_config.to_dict() _lowerCamelCase : Tuple = self.vision_config.to_dict() _lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
72
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Optional[int] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : str = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] _lowerCamelCase : Optional[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] _lowerCamelCase : Any = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] _lowerCamelCase : str = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : int = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) )
72
1
"""simple docstring""" import qiskit def snake_case_ ( A_ : int = 2 ): '''simple docstring''' _lowerCamelCase : List[str] = qubits # Using Aer's simulator _lowerCamelCase : Any = qiskit.Aer.get_backend('''aer_simulator''' ) # Creating a Quantum Circuit acting on the q register _lowerCamelCase : Dict = qiskit.QuantumCircuit(A_, A_ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1, A_ ): # Adding CX (CNOT) gate circuit.cx(i - 1, A_ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(A_ ) ), list(range(A_ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator _lowerCamelCase : Union[str, Any] = qiskit.execute(A_, A_, shots=10_00 ) return job.result().get_counts(A_ ) if __name__ == "__main__": print(F"""Total count for various states are: {quantum_entanglement(3)}""")
361
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int lowerCAmelCase__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __snake_case ( datasets.BuilderConfig): snake_case__ : Optional[datasets.Features] = None def snake_case_ ( A_ : "pyspark.sql.DataFrame", A_ : List[int], ): '''simple docstring''' import pyspark def generate_fn(): _lowerCamelCase : int = df.select('''*''', pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: _lowerCamelCase : Any = df_with_partition_id.select('''*''' ).where(F'''part_id = {partition_id}''' ).drop('''part_id''' ) _lowerCamelCase : Optional[int] = partition_df.collect() _lowerCamelCase : List[str] = 0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class __snake_case ( _BaseExamplesIterable): def __init__( self : Tuple , __lowerCAmelCase : "pyspark.sql.DataFrame" , __lowerCAmelCase : Optional[int]=None , ): """simple docstring""" _lowerCamelCase : Dict = df _lowerCamelCase : Union[str, Any] = partition_order or range(self.df.rdd.getNumPartitions() ) _lowerCamelCase : Dict = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : List[Any] ): """simple docstring""" yield from self.generate_examples_fn() def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : np.random.Generator ): """simple docstring""" _lowerCamelCase : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__lowerCAmelCase ) return SparkExamplesIterable(self.df , partition_order=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.split_shard_indices_by_worker(__lowerCAmelCase , __lowerCAmelCase ) return SparkExamplesIterable(self.df , partition_order=__lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return len(self.partition_order ) class __snake_case ( datasets.DatasetBuilder): snake_case__ : List[Any] = SparkConfig def __init__( self : Union[str, Any] , __lowerCAmelCase : "pyspark.sql.DataFrame" , __lowerCAmelCase : str = None , __lowerCAmelCase : str = None , **__lowerCAmelCase : int , ): """simple docstring""" import pyspark _lowerCamelCase : Optional[int] = pyspark.sql.SparkSession.builder.getOrCreate() _lowerCamelCase : int = df _lowerCamelCase : Any = working_dir super().__init__( cache_dir=__lowerCAmelCase , config_name=str(self.df.semanticHash() ) , **__lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" def create_cache_and_write_probe(__lowerCAmelCase : Optional[int] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = os.path.join(self._cache_dir , '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__lowerCAmelCase , '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''' , '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: _lowerCamelCase : Optional[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__lowerCAmelCase ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : datasets.download.download_manager.DownloadManager ): """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" import pyspark def get_arrow_batch_size(__lowerCAmelCase : Dict ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) _lowerCamelCase : Any = self.df.count() _lowerCamelCase : Union[str, Any] = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. _lowerCamelCase : List[Any] = ( self.df.limit(__lowerCAmelCase ) .repartition(1 ) .mapInArrow(__lowerCAmelCase , '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) _lowerCamelCase : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. _lowerCamelCase : List[str] = min(__lowerCAmelCase , int(approx_total_size / max_shard_size ) ) _lowerCamelCase : Optional[int] = self.df.repartition(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : int , ): """simple docstring""" import pyspark _lowerCamelCase : Optional[Any] = ParquetWriter if file_format == '''parquet''' else ArrowWriter _lowerCamelCase : List[Any] = os.path.join(self._working_dir , os.path.basename(__lowerCAmelCase ) ) if self._working_dir else fpath _lowerCamelCase : Dict = file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. _lowerCamelCase : str = self.config.features _lowerCamelCase : Dict = self._writer_batch_size _lowerCamelCase : List[str] = self._fs.storage_options def write_arrow(__lowerCAmelCase : List[str] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. _lowerCamelCase : List[str] = pyspark.TaskContext().taskAttemptId() _lowerCamelCase : Any = next(__lowerCAmelCase , __lowerCAmelCase ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) _lowerCamelCase : List[Any] = 0 _lowerCamelCase : Optional[int] = writer_class( features=__lowerCAmelCase , path=working_fpath.replace('''SSSSS''' , f'''{shard_id:05d}''' ).replace('''TTTTT''' , f'''{task_id:05d}''' ) , writer_batch_size=__lowerCAmelCase , storage_options=__lowerCAmelCase , embed_local_files=__lowerCAmelCase , ) _lowerCamelCase : int = pa.Table.from_batches([first_batch] ) writer.write_table(__lowerCAmelCase ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: _lowerCamelCase , _lowerCamelCase : Any = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) shard_id += 1 _lowerCamelCase : Optional[int] = writer_class( features=writer._features , path=working_fpath.replace('''SSSSS''' , f'''{shard_id:05d}''' ).replace('''TTTTT''' , f'''{task_id:05d}''' ) , writer_batch_size=__lowerCAmelCase , storage_options=__lowerCAmelCase , embed_local_files=__lowerCAmelCase , ) _lowerCamelCase : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(__lowerCAmelCase ) if writer._num_bytes > 0: _lowerCamelCase , _lowerCamelCase : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__lowerCAmelCase ) ): _lowerCamelCase : Optional[Any] = os.path.join(os.path.dirname(__lowerCAmelCase ) , os.path.basename(__lowerCAmelCase ) ) shutil.move(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = ( self.df.mapInArrow(__lowerCAmelCase , '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ) , pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ) , pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ) , pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : "datasets.SplitGenerator" , __lowerCAmelCase : str = "arrow" , __lowerCAmelCase : Optional[Union[str, int]] = None , __lowerCAmelCase : Optional[int] = None , **__lowerCAmelCase : Tuple , ): """simple docstring""" self._validate_cache_dir() _lowerCamelCase : str = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__lowerCAmelCase ) _lowerCamelCase : str = not is_remote_filesystem(self._fs ) _lowerCamelCase : Tuple = os.path.join if is_local else posixpath.join _lowerCamelCase : int = '''-TTTTT-SSSSS-of-NNNNN''' _lowerCamelCase : Tuple = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' _lowerCamelCase : List[Any] = path_join(self._output_dir , __lowerCAmelCase ) _lowerCamelCase : List[Any] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : str = 0 _lowerCamelCase : int = [] _lowerCamelCase : List[str] = [] for task_id, content in self._prepare_split_single(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__lowerCAmelCase ) _lowerCamelCase : int = total_num_examples _lowerCamelCase : str = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: _lowerCamelCase : Optional[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. _lowerCamelCase : str = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int , ): rename( __lowerCAmelCase , fpath.replace('''SSSSS''' , f'''{shard_id:05d}''' ).replace('''TTTTT''' , f'''{task_id:05d}''' ) , fpath.replace('''TTTTT-SSSSS''' , f'''{global_shard_id:05d}''' ).replace('''NNNNN''' , f'''{total_shards:05d}''' ) , ) _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Any = 0 for i in range(len(__lowerCAmelCase ) ): _lowerCamelCase , _lowerCamelCase : Dict = task_id_and_num_shards[i] for shard_id in range(__lowerCAmelCase ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__lowerCAmelCase , len(__lowerCAmelCase ) ).map(lambda __lowerCAmelCase : _rename_shard(*__lowerCAmelCase ) ).collect() else: # don't use any pattern _lowerCamelCase : Any = 0 _lowerCamelCase : List[str] = task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''' , f'''{shard_id:05d}''' ).replace('''TTTTT''' , f'''{task_id:05d}''' ) , fpath.replace(__lowerCAmelCase , '''''' ) , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : "datasets.SplitGenerator" , ): """simple docstring""" return SparkExamplesIterable(self.df )
175
0
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict A_ : Any = namedtuple( '_TestCommandArgs', [ 'dataset', 'name', 'cache_dir', 'data_dir', 'all_configs', 'save_infos', 'ignore_verifications', 'force_redownload', 'clear_cache', ], defaults=[None, None, None, False, False, False, False, False], ) def UpperCamelCase (lowercase_: Any , lowercase_: List[str] ) -> Optional[int]: return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def UpperCamelCase (lowercase_: str ) -> str: A__ : List[str] = _TestCommandArgs(dataset=lowercase_ , all_configs=lowercase_ , save_infos=lowercase_ ) A__ : int = TestCommand(*lowercase_ ) test_command.run() A__ : Optional[Any] = os.path.join(lowercase_ , """README.md""" ) assert os.path.exists(lowercase_ ) A__ : Dict = DatasetInfosDict.from_directory(lowercase_ ) A__ : str = DatasetInfosDict( { """default""": DatasetInfo( features=Features( { """tokens""": Sequence(Value("""string""" ) ), """ner_tags""": Sequence( ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ), """langs""": Sequence(Value("""string""" ) ), """spans""": Sequence(Value("""string""" ) ), } ) , splits=[ { """name""": """train""", """num_bytes""": 2351563, """num_examples""": 10000, }, { """name""": """validation""", """num_bytes""": 238418, """num_examples""": 1000, }, ] , download_size=3940680 , dataset_size=2589981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: A__ , A__ : Optional[Any] = getattr(dataset_infos["""default"""] , lowercase_ ), getattr(expected_dataset_infos["""default"""] , lowercase_ ) if key == "num_bytes": assert is_apercent_close(lowercase_ , lowercase_ ) elif key == "splits": assert list(lowercase_ ) == list(lowercase_ ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
192
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def UpperCamelCase (lowercase_: List[str] , lowercase_: Optional[int] ) -> List[str]: A__ : Tuple = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) A__ : List[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ), ] , ) def UpperCamelCase (lowercase_: str , lowercase_: DatasetInfo ) -> List[Any]: A__ : Union[str, Any] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) A__ : List[Any] = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , """dataset_info.json""" ) ) def UpperCamelCase () -> List[Any]: A__ : Union[str, Any] = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) A__ : Dict = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) A__ : Union[str, Any] = yaml.safe_dump(lowercase_ ) A__ : List[Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def UpperCamelCase () -> List[str]: A__ : Optional[int] = DatasetInfo() A__ : List[Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=42 ), """v2""": DatasetInfo(dataset_size=1337 ), } ), ] , ) def UpperCamelCase (lowercase_: Tuple , lowercase_: DatasetInfosDict ) -> Optional[Any]: A__ : List[Any] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) A__ : Dict = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): A__ : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml A__ : List[str] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , """README.md""" ) )
192
1
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase__ = ''' Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior") >>> pipe_prior.to("cuda") >>> prompt = "red cat, 4k photo" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder") >>> pipe.to("cuda") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save("cat.png") ``` ''' def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=8 ): """simple docstring""" UpperCamelCase = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 UpperCamelCase = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class _lowerCamelCase ( _a ): def __init__(self , __a , __a , __a , ) -> int: super().__init__() self.register_modules( unet=__lowerCamelCase , scheduler=__lowerCamelCase , movq=__lowerCamelCase , ) UpperCamelCase = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_ (self , __a , __a , __a , __a , __a , __a ) -> str: if latents is None: UpperCamelCase = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=__lowerCamelCase , dtype=__lowerCamelCase ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) UpperCamelCase = latents.to(__lowerCamelCase ) UpperCamelCase = latents * scheduler.init_noise_sigma return latents def snake_case_ (self , __a=0 ) -> List[Any]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCamelCase = torch.device(F"cuda:{gpu_id}" ) UpperCamelCase = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__lowerCamelCase , __lowerCamelCase ) def snake_case_ (self , __a=0 ) -> Dict: if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) UpperCamelCase = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=__lowerCamelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) UpperCamelCase = None for cpu_offloaded_model in [self.unet, self.movq]: UpperCamelCase = cpu_offload_with_hook(__lowerCamelCase , __lowerCamelCase , prev_module_hook=__lowerCamelCase ) # We'll offload the last model manually. UpperCamelCase = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_ (self ) -> Dict: if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__lowerCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__lowerCamelCase ) def __call__(self , __a , __a , __a = 5_12 , __a = 5_12 , __a = 1_00 , __a = 4.0 , __a = 1 , __a = None , __a = None , __a = "pil" , __a = True , ) -> List[str]: UpperCamelCase = self._execution_device UpperCamelCase = guidance_scale > 1.0 if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase = torch.cat(__lowerCamelCase , dim=0 ) UpperCamelCase = image_embeds.shape[0] * num_images_per_prompt if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase = torch.cat(__lowerCamelCase , dim=0 ) if do_classifier_free_guidance: UpperCamelCase = image_embeds.repeat_interleave(__lowerCamelCase , dim=0 ) UpperCamelCase = negative_image_embeds.repeat_interleave(__lowerCamelCase , dim=0 ) UpperCamelCase = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase , device=__lowerCamelCase ) UpperCamelCase = self.scheduler.timesteps UpperCamelCase = self.unet.config.in_channels UpperCamelCase = downscale_height_and_width(__lowerCamelCase , __lowerCamelCase , self.movq_scale_factor ) # create initial latent UpperCamelCase = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(__lowerCamelCase ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase = {"""image_embeds""": image_embeds} UpperCamelCase = self.unet( sample=__lowerCamelCase , timestep=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , added_cond_kwargs=__lowerCamelCase , return_dict=__lowerCamelCase , )[0] if do_classifier_free_guidance: UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) UpperCamelCase = noise_pred.chunk(2 ) UpperCamelCase = variance_pred.chunk(2 ) UpperCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) UpperCamelCase = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase = self.scheduler.step( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , generator=__lowerCamelCase , )[0] # post-processing UpperCamelCase = self.movq.decode(__lowerCamelCase , force_not_quantize=__lowerCamelCase )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: UpperCamelCase = image * 0.5 + 0.5 UpperCamelCase = image.clamp(0 , 1 ) UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCamelCase = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCamelCase )
368
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase__ = NewType('''DataClass''', Any) lowerCAmelCase__ = NewType('''DataClassType''', Any) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = {str(_SCREAMING_SNAKE_CASE ): choice for choice in choices} return lambda _SCREAMING_SNAKE_CASE : str_to_choice.get(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def a__ ( *, _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = dataclasses.MISSING , _SCREAMING_SNAKE_CASE = dataclasses.MISSING , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ): """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls UpperCamelCase = {} if aliases is not None: UpperCamelCase = aliases if help is not None: UpperCamelCase = help return dataclasses.field(metadata=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , default_factory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) class _lowerCamelCase ( _lowercase ): UpperCAmelCase_ = 42 def __init__(self , __a , **__a ) -> Any: # To make the default appear when using --help if "formatter_class" not in kwargs: UpperCamelCase = ArgumentDefaultsHelpFormatter super().__init__(**__a ) if dataclasses.is_dataclass(__a ): UpperCamelCase = [dataclass_types] UpperCamelCase = list(__a ) for dtype in self.dataclass_types: self._add_dataclass_arguments(__a ) @staticmethod def snake_case_ (__a , __a ) -> Optional[Any]: UpperCamelCase = F"--{field.name}" UpperCamelCase = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , __a ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) UpperCamelCase = kwargs.pop("aliases" , [] ) if isinstance(__a , __a ): UpperCamelCase = [aliases] UpperCamelCase = getattr(field.type , "__origin__" , field.type ) if origin_type is Union or (hasattr(__a , "UnionType" ) and isinstance(__a , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(__a ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." F" Problem encountered in field '{field.name}'." ) if type(__a ) not in field.type.__args__: # filter `str` in Union UpperCamelCase = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] UpperCamelCase = getattr(field.type , "__origin__" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) UpperCamelCase = ( field.type.__args__[0] if isinstance(__a , field.type.__args__[1] ) else field.type.__args__[1] ) UpperCamelCase = getattr(field.type , "__origin__" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) UpperCamelCase = {} if origin_type is Literal or (isinstance(field.type , __a ) and issubclass(field.type , __a )): if origin_type is Literal: UpperCamelCase = field.type.__args__ else: UpperCamelCase = [x.value for x in field.type] UpperCamelCase = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: UpperCamelCase = field.default else: UpperCamelCase = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument UpperCamelCase = copy(__a ) # Hack because type=bool in argparse does not behave as we want. UpperCamelCase = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. UpperCamelCase = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way UpperCamelCase = default # This tells argparse we accept 0 or 1 value after --field_name UpperCamelCase = "?" # This is the value that will get picked if we do --field_name (without value) UpperCamelCase = True elif isclass(__a ) and issubclass(__a , __a ): UpperCamelCase = field.type.__args__[0] UpperCamelCase = "+" if field.default_factory is not dataclasses.MISSING: UpperCamelCase = field.default_factory() elif field.default is dataclasses.MISSING: UpperCamelCase = True else: UpperCamelCase = field.type if field.default is not dataclasses.MISSING: UpperCamelCase = field.default elif field.default_factory is not dataclasses.MISSING: UpperCamelCase = field.default_factory() else: UpperCamelCase = True parser.add_argument(__a , *__a , **__a ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): UpperCamelCase = False parser.add_argument(F"--no_{field.name}" , action="store_false" , dest=field.name , **__a ) def snake_case_ (self , __a ) -> List[Any]: if hasattr(__a , "_argument_group_name" ): UpperCamelCase = self.add_argument_group(dtype._argument_group_name ) else: UpperCamelCase = self try: UpperCamelCase = get_type_hints(__a ) except NameError: raise RuntimeError( F"Type resolution failed for {dtype}. Try declaring the class in global scope or " "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__a ): UpperCamelCase = ".".join(map(__a , sys.version_info[:3] ) ) raise RuntimeError( F"Type resolution failed for {dtype} on Python {python_version}. Try removing " "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(__a ): if not field.init: continue UpperCamelCase = type_hints[field.name] self._parse_dataclass_field(__a , __a ) def snake_case_ (self , __a=None , __a=False , __a=True , __a=None , __a=None , ) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): UpperCamelCase = [] if args_filename: args_files.append(Path(__a ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values UpperCamelCase = ArgumentParser() args_file_parser.add_argument(__a , type=__a , action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) UpperCamelCase , UpperCamelCase = args_file_parser.parse_known_args(args=__a ) UpperCamelCase = vars(__a ).get(args_file_flag.lstrip("-" ) , __a ) if cmd_args_file_paths: args_files.extend([Path(__a ) for p in cmd_args_file_paths] ) UpperCamelCase = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last UpperCamelCase = file_args + args if args is not None else file_args + sys.argv[1:] UpperCamelCase , UpperCamelCase = self.parse_known_args(args=__a ) UpperCamelCase = [] for dtype in self.dataclass_types: UpperCamelCase = {f.name for f in dataclasses.fields(__a ) if f.init} UpperCamelCase = {k: v for k, v in vars(__a ).items() if k in keys} for k in keys: delattr(__a , __a ) UpperCamelCase = dtype(**__a ) outputs.append(__a ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(__a ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F"Some specified arguments are not used by the HfArgumentParser: {remaining_args}" ) return (*outputs,) def snake_case_ (self , __a , __a = False ) -> Tuple[DataClass, ...]: UpperCamelCase = set(args.keys() ) UpperCamelCase = [] for dtype in self.dataclass_types: UpperCamelCase = {f.name for f in dataclasses.fields(__a ) if f.init} UpperCamelCase = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) UpperCamelCase = dtype(**__a ) outputs.append(__a ) if not allow_extra_keys and unused_keys: raise ValueError(F"Some keys are not used by the HfArgumentParser: {sorted(__a )}" ) return tuple(__a ) def snake_case_ (self , __a , __a = False ) -> Tuple[DataClass, ...]: with open(Path(__a ) , encoding="utf-8" ) as open_json_file: UpperCamelCase = json.loads(open_json_file.read() ) UpperCamelCase = self.parse_dict(__a , allow_extra_keys=__a ) return tuple(__a ) def snake_case_ (self , __a , __a = False ) -> Tuple[DataClass, ...]: UpperCamelCase = self.parse_dict(yaml.safe_load(Path(__a ).read_text() ) , allow_extra_keys=__a ) return tuple(__a )
244
0
'''simple docstring''' from __future__ import annotations class A_ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : int ) -> None: UpperCAmelCase : List[Any] = data UpperCAmelCase : Node | None = None UpperCAmelCase : Node | None = None def UpperCamelCase( UpperCAmelCase_ ): # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def UpperCamelCase( UpperCAmelCase_ ): return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def UpperCamelCase( UpperCAmelCase_ ): if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def UpperCamelCase( ): # Main function for testing. UpperCAmelCase : Optional[int] = Node(1 ) UpperCAmelCase : str = Node(2 ) UpperCAmelCase : Optional[Any] = Node(3 ) UpperCAmelCase : List[Any] = Node(4 ) UpperCAmelCase : Dict = Node(5 ) UpperCAmelCase : Union[str, Any] = Node(6 ) UpperCAmelCase : Tuple = Node(7 ) UpperCAmelCase : List[Any] = Node(8 ) UpperCAmelCase : Optional[Any] = Node(9 ) print(is_full_binary_tree(UpperCAmelCase_ ) ) print(depth_of_tree(UpperCAmelCase_ ) ) print('Tree is: ' ) display(UpperCAmelCase_ ) if __name__ == "__main__": main()
151
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu lowercase__ = False class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase_ ( self : str ) -> Tuple: return 12 @property def UpperCAmelCase_ ( self : Tuple ) -> Dict: return 12 @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return 32 @property def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: torch.manual_seed(0 ) UpperCAmelCase : Optional[int] = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def UpperCAmelCase_ ( self : List[str] ) -> Tuple: UpperCAmelCase : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: torch.manual_seed(0 ) UpperCAmelCase : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(lowercase_ ) @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: torch.manual_seed(0 ) UpperCAmelCase : Any = 12 UpperCAmelCase : Optional[int] = 12 UpperCAmelCase : Tuple = { 'attention_bias': True, 'cross_attention_dim': 32, 'attention_head_dim': height * width, 'num_attention_heads': 1, 'num_vector_embeds': self.num_embed, 'num_embeds_ada_norm': self.num_embeds_ada_norm, 'norm_num_groups': 32, 'sample_size': width, 'activation_fn': 'geglu-approximate', } UpperCAmelCase : Optional[Any] = TransformeraDModel(**lowercase_ ) return model def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: UpperCAmelCase : Any = 'cpu' UpperCAmelCase : Optional[int] = self.dummy_vqvae UpperCAmelCase : List[str] = self.dummy_text_encoder UpperCAmelCase : str = self.dummy_tokenizer UpperCAmelCase : Dict = self.dummy_transformer UpperCAmelCase : Union[str, Any] = VQDiffusionScheduler(self.num_embed ) UpperCAmelCase : str = LearnedClassifierFreeSamplingEmbeddings(learnable=lowercase_ ) UpperCAmelCase : Optional[Any] = VQDiffusionPipeline( vqvae=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , transformer=lowercase_ , scheduler=lowercase_ , learned_classifier_free_sampling_embeddings=lowercase_ , ) UpperCAmelCase : Optional[int] = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) UpperCAmelCase : Any = 'teddy bear playing in the pool' UpperCAmelCase : List[str] = torch.Generator(device=lowercase_ ).manual_seed(0 ) UpperCAmelCase : List[str] = pipe([prompt] , generator=lowercase_ , num_inference_steps=2 , output_type='np' ) UpperCAmelCase : List[str] = output.images UpperCAmelCase : List[Any] = torch.Generator(device=lowercase_ ).manual_seed(0 ) UpperCAmelCase : Union[str, Any] = pipe( [prompt] , generator=lowercase_ , output_type='np' , return_dict=lowercase_ , num_inference_steps=2 )[0] UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] UpperCAmelCase : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) UpperCAmelCase : Optional[Any] = np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase_ ( self : Any ) -> Dict: UpperCAmelCase : str = 'cpu' UpperCAmelCase : List[str] = self.dummy_vqvae UpperCAmelCase : Tuple = self.dummy_text_encoder UpperCAmelCase : Dict = self.dummy_tokenizer UpperCAmelCase : int = self.dummy_transformer UpperCAmelCase : Optional[int] = VQDiffusionScheduler(self.num_embed ) UpperCAmelCase : List[str] = LearnedClassifierFreeSamplingEmbeddings( learnable=lowercase_ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) UpperCAmelCase : List[Any] = VQDiffusionPipeline( vqvae=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , transformer=lowercase_ , scheduler=lowercase_ , learned_classifier_free_sampling_embeddings=lowercase_ , ) UpperCAmelCase : Optional[int] = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) UpperCAmelCase : Union[str, Any] = 'teddy bear playing in the pool' UpperCAmelCase : Union[str, Any] = torch.Generator(device=lowercase_ ).manual_seed(0 ) UpperCAmelCase : Tuple = pipe([prompt] , generator=lowercase_ , num_inference_steps=2 , output_type='np' ) UpperCAmelCase : List[Any] = output.images UpperCAmelCase : Tuple = torch.Generator(device=lowercase_ ).manual_seed(0 ) UpperCAmelCase : int = pipe( [prompt] , generator=lowercase_ , output_type='np' , return_dict=lowercase_ , num_inference_steps=2 )[0] UpperCAmelCase : Tuple = image[0, -3:, -3:, -1] UpperCAmelCase : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) UpperCAmelCase : Optional[Any] = np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : int ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: UpperCAmelCase : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy' ) UpperCAmelCase : Tuple = VQDiffusionPipeline.from_pretrained('microsoft/vq-diffusion-ithq' ) UpperCAmelCase : str = pipeline.to(lowercase_ ) pipeline.set_progress_bar_config(disable=lowercase_ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though UpperCAmelCase : Any = torch.Generator(device=lowercase_ ).manual_seed(0 ) UpperCAmelCase : Any = pipeline( 'teddy bear playing in the pool' , num_images_per_prompt=1 , generator=lowercase_ , output_type='np' , ) UpperCAmelCase : Dict = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
151
1
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class a__ : def __init__( self : Optional[int] , a : Union[str, Any] , a : Optional[Any]=13 , a : Optional[Any]=7 , a : Optional[int]=True , a : Tuple=True , a : Optional[int]=True , a : Union[str, Any]=True , a : Any=99 , a : Union[str, Any]=16 , a : Optional[Any]=36 , a : Dict=6 , a : Dict=6 , a : Tuple=6 , a : Optional[Any]=37 , a : Optional[int]="gelu" , a : int=0.1 , a : Optional[int]=0.1 , a : Dict=5_12 , a : Tuple=16 , a : Any=2 , a : Dict=0.02 , a : Optional[int]=3 , a : Union[str, Any]=4 , a : str=None , ): """simple docstring""" __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 = embedding_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_hidden_groups __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 SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase = None if self.use_input_mask: __lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase = None if self.use_token_type_ids: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase = None __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, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : List[str] , a : List[Any] , a : Tuple , a : Tuple , a : List[Any] , a : Any , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = AlbertModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , token_type_ids=_lowerCAmelCase ) __lowerCamelCase = model(_lowerCAmelCase , token_type_ids=_lowerCAmelCase ) __lowerCamelCase = model(_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Any , a : int , a : List[Any] , a : str , a : Optional[int] , a : Union[str, Any] , a : int ): """simple docstring""" __lowerCamelCase = AlbertForPreTraining(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , token_type_ids=_lowerCAmelCase , labels=_lowerCAmelCase , sentence_order_label=_lowerCAmelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[str] , a : Union[str, Any] , a : Optional[int] , a : Any , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = AlbertForMaskedLM(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = 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 SCREAMING_SNAKE_CASE__ ( self : Any , a : List[str] , a : int , a : str , a : List[str] , a : List[str] , a : Optional[int] , a : str ): """simple docstring""" __lowerCamelCase = AlbertForQuestionAnswering(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = 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 SCREAMING_SNAKE_CASE__ ( self : Any , a : List[str] , a : int , a : str , a : str , a : Dict , a : int , a : List[str] ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = AlbertForSequenceClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , token_type_ids=_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[str] , a : Union[str, Any] , a : Any , a : Any , a : int , a : str , a : str ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = AlbertForTokenClassification(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = 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 SCREAMING_SNAKE_CASE__ ( self : Any , a : str , a : Any , a : Union[str, Any] , a : Any , a : int , a : Optional[Any] , a : Tuple ): """simple docstring""" __lowerCamelCase = self.num_choices __lowerCamelCase = AlbertForMultipleChoice(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowerCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = model( _lowerCAmelCase , attention_mask=_lowerCAmelCase , token_type_ids=_lowerCAmelCase , labels=_lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.prepare_config_and_inputs() ( __lowerCamelCase ) = config_and_inputs __lowerCamelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class a__ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): lowerCamelCase : List[str] =( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase : Any =( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase : Tuple =True def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : Optional[Any] , a : Any , a : Optional[int]=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase ) if return_labels: if model_class in get_values(_lowerCAmelCase ): __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_lowerCAmelCase ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCAmelCase ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = AlbertModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=_lowerCAmelCase , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase = type self.model_tester.create_and_check_model(*_lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = AlbertModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = AlbertModel.from_pretrained('''albert-base-v2''' ) __lowerCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) __lowerCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCamelCase = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase )[0] __lowerCamelCase = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , _lowerCAmelCase ) __lowerCamelCase = torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCAmelCase , atol=1e-4 ) )
370
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __UpperCAmelCase =get_tests_dir("fixtures/spiece.model") @require_sentencepiece @require_tokenizers class a__ ( UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : Optional[Any] =DebertaVaTokenizer lowerCamelCase : Optional[int] =DebertaVaTokenizerFast lowerCamelCase : Optional[Any] =True lowerCamelCase : Tuple =True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase = DebertaVaTokenizer(a , unk_token='''<unk>''' ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Dict ): """simple docstring""" __lowerCamelCase = '''this is a test''' __lowerCamelCase = '''this is a test''' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = '''<pad>''' __lowerCamelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''[PAD]''' ) self.assertEqual(len(a ) , 3_00_01 ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_00_00 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = ''' \tHeLLo!how \n Are yoU? ''' __lowerCamelCase = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?'''] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , do_lower_case=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , do_lower_case=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" pass @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , split_by_punct=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , split_by_punct=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = ''' \tHeLLo!how \n Are yoU? ''' __lowerCamelCase = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?'''] # fmt: on __lowerCamelCase = DebertaVaTokenizer(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = DebertaVaTokenizerFast(a , do_lower_case=a , split_by_punct=a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(a , add_special_tokens=a ) ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a , add_special_tokens=a ) ) self.assertListEqual(a , a ) __lowerCamelCase = tokenizer.encode(a , add_special_tokens=a ) __lowerCamelCase = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase = self.get_rust_tokenizer() __lowerCamelCase = tokenizer.encode(a ) __lowerCamelCase = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = '''This is a test''' __lowerCamelCase = [13, 1, 43_98, 25, 21, 12_89] __lowerCamelCase = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test'''] __lowerCamelCase = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test'''] __lowerCamelCase = DebertaVaTokenizer(a , keep_accents=a ) __lowerCamelCase = DebertaVaTokenizerFast(a , keep_accents=a ) __lowerCamelCase = tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(a ) self.assertListEqual(a , a ) # fmt: off __lowerCamelCase = '''I was born in 92000, and this is falsé.''' __lowerCamelCase = [13, 1, 23, 3_86, 19, 5_61, 30_50, 15, 17, 48, 25, 82_56, 18, 1, 9] __lowerCamelCase = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ] __lowerCamelCase = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on __lowerCamelCase = tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase = rust_tokenizer.convert_ids_to_tokens(a ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = DebertaVaTokenizer(a ) __lowerCamelCase = tokenizer.encode('''sequence builders''' ) __lowerCamelCase = tokenizer.encode('''multi-sequence build''' ) __lowerCamelCase = tokenizer.build_inputs_with_special_tokens(a ) __lowerCamelCase = tokenizer.build_inputs_with_special_tokens(a , a ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , a ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , a , ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = {'''input_ids''': [[1, 3_98_67, 36, 1_93_90, 4_86, 27, 3_50_52, 8_14_36, 18, 6_06_85, 12_25, 7, 3_50_52, 8_14_36, 18, 93_67, 1_68_99, 18, 1_59_37, 53, 5_94, 7_73, 18, 1_62_87, 3_04_65, 36, 1_59_37, 6, 4_11_39, 38, 3_69_79, 6_07_63, 1_91, 6, 3_41_32, 99, 6, 5_05_38, 3_90, 4_32_30, 6, 3_41_32, 27_79, 2_08_50, 14, 6_99, 10_72, 11_94, 36, 3_82, 1_09_01, 53, 7, 6_99, 10_72, 20_84, 36, 2_04_22, 6_30, 53, 19, 1_05, 30_49, 18_96, 10_53, 1_68_99, 15_06, 11, 3_79_78, 42_43, 7, 12_37, 3_18_69, 2_00, 1_65_66, 6_54, 6, 3_50_52, 8_14_36, 7, 5_56_30, 1_35_93, 4, 2], [1, 26, 1_50_11, 13, 6_67, 8, 10_53, 18, 2_36_11, 12_37, 7_23_56, 1_28_20, 34, 10_41_34, 12_09, 35, 1_33_13, 66_27, 21, 2_02, 3_47, 7, 1_64, 23_99, 11, 46, 44_85, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 12_32, 28_64, 1_57_85, 1_49_51, 1_05, 5, 85_81, 12_50, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
237
0
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters lowercase__ = (720, 1280) # Height, Width lowercase__ = (0.4, 0.6) # if height or width lower than this scale, drop it. lowercase__ = 1 / 100 lowercase__ = """""" lowercase__ = """""" lowercase__ = """""" lowercase__ = 250 def _snake_case ( ): _lowerCamelCase, _lowerCamelCase : str = get_dataset(lowercase__ , lowercase__ ) for index in range(lowercase__ ): _lowerCamelCase : List[str] = random.sample(range(len(lowercase__ ) ) , 4 ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : str = update_image_and_anno( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , filter_scale=lowercase__ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _lowerCamelCase : int = random_chars(32 ) _lowerCamelCase : Dict = path.split(os.sep )[-1].rsplit('.' , 1 )[0] _lowerCamelCase : List[str] = f'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(f'''{file_root}.jpg''' , lowercase__ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) _lowerCamelCase : Optional[int] = [] for anno in new_annos: _lowerCamelCase : Union[str, Any] = anno[3] - anno[1] _lowerCamelCase : Tuple = anno[4] - anno[2] _lowerCamelCase : Union[str, Any] = anno[1] + width / 2 _lowerCamelCase : Optional[int] = anno[2] + height / 2 _lowerCamelCase : int = f'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(lowercase__ ) with open(f'''{file_root}.txt''' , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _snake_case ( lowercase__ , lowercase__ ): _lowerCamelCase : Dict = [] _lowerCamelCase : int = [] for label_file in glob.glob(os.path.join(lowercase__ , '*.txt' ) ): _lowerCamelCase : List[Any] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(lowercase__ ) as in_file: _lowerCamelCase : int = in_file.readlines() _lowerCamelCase : Union[str, Any] = os.path.join(lowercase__ , f'''{label_name}.jpg''' ) _lowerCamelCase : List[Any] = [] for obj_list in obj_lists: _lowerCamelCase : int = obj_list.rstrip('\n' ).split(' ' ) _lowerCamelCase : List[str] = float(obj[1] ) - float(obj[3] ) / 2 _lowerCamelCase : str = float(obj[2] ) - float(obj[4] ) / 2 _lowerCamelCase : str = float(obj[1] ) + float(obj[3] ) / 2 _lowerCamelCase : Optional[int] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(lowercase__ ) labels.append(lowercase__ ) return img_paths, labels def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ = 0.0 , ): _lowerCamelCase : Optional[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) _lowerCamelCase : Optional[int] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCamelCase : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCamelCase : List[str] = int(scale_x * output_size[1] ) _lowerCamelCase : str = int(scale_y * output_size[0] ) _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : Tuple = [] for i, index in enumerate(lowercase__ ): _lowerCamelCase : Optional[Any] = all_img_list[index] path_list.append(lowercase__ ) _lowerCamelCase : str = all_annos[index] _lowerCamelCase : Union[str, Any] = cva.imread(lowercase__ ) if i == 0: # top-left _lowerCamelCase : Dict = cva.resize(lowercase__ , (divid_point_x, divid_point_y) ) _lowerCamelCase : Dict = img for bbox in img_annos: _lowerCamelCase : Optional[int] = bbox[1] * scale_x _lowerCamelCase : str = bbox[2] * scale_y _lowerCamelCase : List[str] = bbox[3] * scale_x _lowerCamelCase : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right _lowerCamelCase : int = cva.resize(lowercase__ , (output_size[1] - divid_point_x, divid_point_y) ) _lowerCamelCase : List[Any] = img for bbox in img_annos: _lowerCamelCase : Union[str, Any] = scale_x + bbox[1] * (1 - scale_x) _lowerCamelCase : List[str] = bbox[2] * scale_y _lowerCamelCase : int = scale_x + bbox[3] * (1 - scale_x) _lowerCamelCase : Optional[int] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left _lowerCamelCase : Optional[Any] = cva.resize(lowercase__ , (divid_point_x, output_size[0] - divid_point_y) ) _lowerCamelCase : int = img for bbox in img_annos: _lowerCamelCase : Optional[int] = bbox[1] * scale_x _lowerCamelCase : List[Any] = scale_y + bbox[2] * (1 - scale_y) _lowerCamelCase : Optional[int] = bbox[3] * scale_x _lowerCamelCase : Any = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right _lowerCamelCase : Tuple = cva.resize( lowercase__ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) _lowerCamelCase : Dict = img for bbox in img_annos: _lowerCamelCase : str = scale_x + bbox[1] * (1 - scale_x) _lowerCamelCase : Tuple = scale_y + bbox[2] * (1 - scale_y) _lowerCamelCase : List[str] = scale_x + bbox[3] * (1 - scale_x) _lowerCamelCase : Dict = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: _lowerCamelCase : List[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def _snake_case ( lowercase__ ): assert number_char > 1, "The number of character should greater than 1" _lowerCamelCase : str = ascii_lowercase + digits return "".join(random.choice(lowercase__ ) for _ in range(lowercase__ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
96
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version lowercase__ = get_logger(__name__) class lowerCAmelCase__ : '''simple docstring''' lowerCamelCase__ = """dummy_data""" lowerCamelCase__ = """datasets""" lowerCamelCase__ = False def __init__( self , lowercase , lowercase , lowercase , lowercase = None , lowercase = False , lowercase = True , lowercase = None , ): _lowerCamelCase : Optional[Any] = 0 _lowerCamelCase : Dict = dataset_name _lowerCamelCase : Union[str, Any] = cache_dir _lowerCamelCase : Dict = use_local_dummy_data _lowerCamelCase : Tuple = config # download_callbacks take a single url as input _lowerCamelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root _lowerCamelCase : Any = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general _lowerCamelCase : str = str(lowercase ) # to be downloaded _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : int = None @property def A_ ( self ): if self._dummy_file is None: _lowerCamelCase : Tuple = self.download_dummy_data() return self._dummy_file @property def A_ ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('dummy' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('dummy' , self.version_name ) @property def A_ ( self ): return os.path.join(self.dummy_data_folder , 'dummy_data.zip' ) def A_ ( self ): _lowerCamelCase : List[str] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) _lowerCamelCase : int = cached_path( lowercase , cache_dir=self.cache_dir , extract_compressed_file=lowercase , force_extract=lowercase ) return os.path.join(lowercase , self.dummy_file_name ) @property def A_ ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def A_ ( self ): if self._bucket_url is None: _lowerCamelCase : List[Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '/' ) ) return self._bucket_url @property def A_ ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '/' ).split('/' )[:-1] ) def A_ ( self , lowercase , *lowercase ): if self.load_existing_dummy_data: # dummy data is downloaded and tested _lowerCamelCase : Union[str, Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned _lowerCamelCase : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(lowercase , lowercase ): return self.create_dummy_data_dict(lowercase , lowercase ) elif isinstance(lowercase , (list, tuple) ): return self.create_dummy_data_list(lowercase , lowercase ) else: return self.create_dummy_data_single(lowercase , lowercase ) def A_ ( self , lowercase , *lowercase ): return self.download_and_extract(lowercase ) def A_ ( self , lowercase , lowercase ): return self.download_and_extract(lowercase ) def A_ ( self , lowercase , *lowercase , **lowercase ): return path def A_ ( self ): return {} def A_ ( self , lowercase , lowercase ): _lowerCamelCase : Optional[int] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(lowercase , lowercase ): for single_url in single_urls: download_callback(lowercase ) else: _lowerCamelCase : List[Any] = single_urls download_callback(lowercase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(lowercase , lowercase ): _lowerCamelCase : List[Any] = [os.path.join(lowercase , urllib.parse.quote_plus(Path(lowercase ).name ) ) for x in single_urls] else: _lowerCamelCase : Optional[int] = single_urls _lowerCamelCase : List[Any] = os.path.join(lowercase , urllib.parse.quote_plus(Path(lowercase ).name ) ) _lowerCamelCase : int = value # make sure that values are unique if all(isinstance(lowercase , lowercase ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique _lowerCamelCase : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def A_ ( self , lowercase , lowercase ): _lowerCamelCase : Optional[Any] = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one _lowerCamelCase : List[str] = all(bool(re.findall('[0-9]{3,}-of-[0-9]{3,}' , lowercase ) ) for url in data_url ) _lowerCamelCase : int = all( url.startswith('https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): _lowerCamelCase : List[str] = [data_url[0]] * len(lowercase ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(lowercase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _lowerCamelCase : str = os.path.join(lowercase , urllib.parse.quote_plus(single_url.split('/' )[-1] ) ) dummy_data_list.append(lowercase ) return dummy_data_list def A_ ( self , lowercase , lowercase ): for download_callback in self.download_callbacks: download_callback(lowercase ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus _lowerCamelCase : Tuple = os.path.join(lowercase , urllib.parse.quote_plus(data_url.split('/' )[-1] ) ) if os.path.exists(lowercase ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def A_ ( self ): pass def A_ ( self ): pass def A_ ( self , lowercase ): def _iter_archive_members(lowercase ): # this preserves the order of the members inside the ZIP archive _lowerCamelCase : str = Path(self.dummy_file ).parent _lowerCamelCase : Union[str, Any] = path.relative_to(lowercase ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: _lowerCamelCase : List[str] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(lowercase ) _lowerCamelCase : Optional[int] = Path(lowercase ) _lowerCamelCase : Dict = _iter_archive_members(lowercase ) if self.use_local_dummy_data else path.rglob('*' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('.', '__') ): yield file_path.relative_to(lowercase ).as_posix(), file_path.open('rb' ) def A_ ( self , lowercase ): if not isinstance(lowercase , lowercase ): _lowerCamelCase : List[str] = [paths] for path in paths: if os.path.isfile(lowercase ): if os.path.basename(lowercase ).startswith(('.', '__') ): return yield path else: for dirpath, dirnames, filenames in os.walk(lowercase ): if os.path.basename(lowercase ).startswith(('.', '__') ): continue dirnames.sort() for filename in sorted(lowercase ): if filename.startswith(('.', '__') ): continue yield os.path.join(lowercase , lowercase )
96
1
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup lowerCamelCase__ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : Optional[int] , **__a : Any ) -> Any: requires_backends(self , ["bs4"] ) super().__init__(**__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[Any] ) -> Union[str, Any]: _UpperCamelCase : int = [] _UpperCamelCase : Optional[int] = [] _UpperCamelCase : Any = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag _UpperCamelCase : Any = parent.find_all(child.name , recursive=__a ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__a ) else next(i for i, s in enumerate(__a , 1 ) if s is child ) ) _UpperCamelCase : List[Any] = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : List[Any] ) -> List[Any]: _UpperCamelCase : Any = BeautifulSoup(__a , "html.parser" ) _UpperCamelCase : Dict = [] _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[str] = [] for element in html_code.descendants: if type(__a ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue _UpperCamelCase : List[str] = html.unescape(__a ).strip() if not text_in_this_tag: continue all_doc_strings.append(__a ) _UpperCamelCase : Union[str, Any] = self.xpath_soup(__a ) stringaxtag_seq.append(__a ) stringaxsubs_seq.append(__a ) if len(__a ) != len(__a ): raise ValueError("Number of doc strings and xtags does not correspond" ) if len(__a ) != len(__a ): raise ValueError("Number of doc strings and xsubs does not correspond" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Tuple , __a : int ) -> List[Any]: _UpperCamelCase : int = "" for tagname, subs in zip(__a , __a ): xpath += F'''/{tagname}''' if subs != 0: xpath += F'''[{subs}]''' return xpath def __call__( self : List[str] , __a : str ) -> BatchFeature: _UpperCamelCase : str = False # Check that strings has a valid type if isinstance(__a , __a ): _UpperCamelCase : int = True elif isinstance(__a , (list, tuple) ): if len(__a ) == 0 or isinstance(html_strings[0] , __a ): _UpperCamelCase : List[str] = True if not valid_strings: raise ValueError( "HTML strings must of type `str`, `List[str]` (batch of examples), " F'''but is of type {type(__a )}.''' ) _UpperCamelCase : Optional[Any] = bool(isinstance(__a , (list, tuple) ) and (isinstance(html_strings[0] , __a )) ) if not is_batched: _UpperCamelCase : str = [html_strings] # Get nodes + xpaths _UpperCamelCase : Optional[int] = [] _UpperCamelCase : Any = [] for html_string in html_strings: _UpperCamelCase : str = self.get_three_from_single(__a ) nodes.append(__a ) _UpperCamelCase : Any = [] for node, tag_list, sub_list in zip(__a , __a , __a ): _UpperCamelCase : Dict = self.construct_xpath(__a , __a ) xpath_strings.append(__a ) xpaths.append(__a ) # return as Dict _UpperCamelCase : Optional[Any] = {"nodes": nodes, "xpaths": xpaths} _UpperCamelCase : Any = BatchFeature(data=__a , tensor_type=__a ) return encoded_inputs
359
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def __SCREAMING_SNAKE_CASE ( *__a : int , **__a : int ) -> List[Any]: pass @is_pipeline_test @require_vision @require_timm @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = MODEL_FOR_OBJECT_DETECTION_MAPPING def __SCREAMING_SNAKE_CASE ( self : Any , __a : Union[str, Any] , __a : Optional[int] , __a : str ) -> Optional[Any]: _UpperCamelCase : List[Any] = ObjectDetectionPipeline(model=__a , image_processor=__a ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : Union[str, Any] ) -> int: _UpperCamelCase : Any = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 ) self.assertGreater(len(__a ) , 0 ) for detected_object in outputs: self.assertEqual( __a , { "score": ANY(__a ), "label": ANY(__a ), "box": {"xmin": ANY(__a ), "ymin": ANY(__a ), "xmax": ANY(__a ), "ymax": ANY(__a )}, } , ) import datasets _UpperCamelCase : str = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) _UpperCamelCase : List[Any] = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] _UpperCamelCase : List[Any] = object_detector(__a , threshold=0.0 ) self.assertEqual(len(__a ) , len(__a ) ) for outputs in batch_outputs: self.assertGreater(len(__a ) , 0 ) for detected_object in outputs: self.assertEqual( __a , { "score": ANY(__a ), "label": ANY(__a ), "box": {"xmin": ANY(__a ), "ymin": ANY(__a ), "xmax": ANY(__a ), "ymax": ANY(__a )}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF" ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: pass @require_torch def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[str] = "hf-internal-testing/tiny-detr-mobilenetsv3" _UpperCamelCase : Optional[int] = AutoModelForObjectDetection.from_pretrained(__a ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained(__a ) _UpperCamelCase : List[Any] = ObjectDetectionPipeline(model=__a , feature_extractor=__a ) _UpperCamelCase : int = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ] , ) _UpperCamelCase : Any = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], [ {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], ] , ) @require_torch @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: _UpperCamelCase : str = "facebook/detr-resnet-50" _UpperCamelCase : Union[str, Any] = AutoModelForObjectDetection.from_pretrained(__a ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained(__a ) _UpperCamelCase : Union[str, Any] = ObjectDetectionPipeline(model=__a , feature_extractor=__a ) _UpperCamelCase : Tuple = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) _UpperCamelCase : List[str] = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: _UpperCamelCase : Dict = "facebook/detr-resnet-50" _UpperCamelCase : Optional[Any] = pipeline("object-detection" , model=__a ) _UpperCamelCase : str = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) _UpperCamelCase : Tuple = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: _UpperCamelCase : Tuple = 0.99_85 _UpperCamelCase : List[Any] = "facebook/detr-resnet-50" _UpperCamelCase : List[str] = pipeline("object-detection" , model=__a ) _UpperCamelCase : Any = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=__a ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) @require_torch @require_pytesseract @slow def __SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: _UpperCamelCase : Optional[Any] = "Narsil/layoutlmv3-finetuned-funsd" _UpperCamelCase : int = 0.99_93 _UpperCamelCase : str = pipeline("object-detection" , model=__a , threshold=__a ) _UpperCamelCase : Union[str, Any] = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, ] , )
310
0
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''nvidia/segformer-b0-finetuned-ade-512-512''': ( '''https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json''' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : List[Any] = """segformer""" def __init__( self , __lowercase=3 , __lowercase=4 , __lowercase=[2, 2, 2, 2] , __lowercase=[8, 4, 2, 1] , __lowercase=[32, 64, 160, 256] , __lowercase=[7, 3, 3, 3] , __lowercase=[4, 2, 2, 2] , __lowercase=[1, 2, 5, 8] , __lowercase=[4, 4, 4, 4] , __lowercase="gelu" , __lowercase=0.0 , __lowercase=0.0 , __lowercase=0.1 , __lowercase=0.02 , __lowercase=0.1 , __lowercase=1E-6 , __lowercase=256 , __lowercase=255 , **__lowercase , ) -> List[Any]: super().__init__(**__lowercase) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( '''Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be''' ''' removed, as the behaviour will default to that of reshape_last_stage = True.''' , __lowercase , ) __UpperCamelCase :Tuple = num_channels __UpperCamelCase :int = num_encoder_blocks __UpperCamelCase :Tuple = depths __UpperCamelCase :Dict = sr_ratios __UpperCamelCase :List[Any] = hidden_sizes __UpperCamelCase :str = patch_sizes __UpperCamelCase :Tuple = strides __UpperCamelCase :str = mlp_ratios __UpperCamelCase :str = num_attention_heads __UpperCamelCase :Optional[Any] = hidden_act __UpperCamelCase :Optional[Any] = hidden_dropout_prob __UpperCamelCase :str = attention_probs_dropout_prob __UpperCamelCase :List[Any] = classifier_dropout_prob __UpperCamelCase :Optional[int] = initializer_range __UpperCamelCase :Dict = drop_path_rate __UpperCamelCase :List[Any] = layer_norm_eps __UpperCamelCase :Optional[int] = decoder_hidden_size __UpperCamelCase :Union[str, Any] = kwargs.get('''reshape_last_stage''' , __lowercase) __UpperCamelCase :Union[str, Any] = semantic_loss_ignore_index class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Any = version.parse("""1.11""" ) @property def UpperCamelCase__ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def UpperCamelCase__ ( self) -> float: return 1E-4 @property def UpperCamelCase__ ( self) -> int: return 12
43
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __lowercase = logging.get_logger(__name__) class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Optional[Any] = ["""pixel_values"""] def __init__( self , __lowercase = True , __lowercase = 32 , __lowercase=PILImageResampling.BILINEAR , __lowercase = True , **__lowercase , ) -> None: __UpperCamelCase :Optional[int] = do_resize __UpperCamelCase :Any = do_rescale __UpperCamelCase :str = size_divisor __UpperCamelCase :Dict = resample super().__init__(**__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase = None , **__lowercase) -> np.ndarray: __UpperCamelCase , __UpperCamelCase :int = get_image_size(__lowercase) # Rounds the height and width down to the closest multiple of size_divisor __UpperCamelCase :List[Any] = height // size_divisor * size_divisor __UpperCamelCase :List[str] = width // size_divisor * size_divisor __UpperCamelCase :str = resize(__lowercase , (new_h, new_w) , resample=__lowercase , data_format=__lowercase , **__lowercase) return image def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase = None , **__lowercase) -> np.ndarray: return rescale(image=__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase = None , __lowercase = None , __lowercase=None , __lowercase = None , __lowercase = None , __lowercase = ChannelDimension.FIRST , **__lowercase , ) -> BatchFeature: __UpperCamelCase :Union[str, Any] = do_resize if do_resize is not None else self.do_resize __UpperCamelCase :Tuple = do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase :List[str] = size_divisor if size_divisor is not None else self.size_divisor __UpperCamelCase :List[Any] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''') __UpperCamelCase :List[Any] = make_list_of_images(__lowercase) if not valid_images(__lowercase): raise ValueError('''Invalid image(s)''') # All transformations expect numpy arrays. __UpperCamelCase :Optional[Any] = [to_numpy_array(__lowercase) for img in images] if do_resize: __UpperCamelCase :List[str] = [self.resize(__lowercase , size_divisor=__lowercase , resample=__lowercase) for image in images] if do_rescale: __UpperCamelCase :Dict = [self.rescale(__lowercase , scale=1 / 255) for image in images] __UpperCamelCase :str = [to_channel_dimension_format(__lowercase , __lowercase) for image in images] __UpperCamelCase :int = {'''pixel_values''': images} return BatchFeature(data=__lowercase , tensor_type=__lowercase)
43
1
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class a__ : def __init__( self , A=2 , A=3 , A=64 , A=None ) -> List[Any]: '''simple docstring''' a = np.random.default_rng(A ) a = length a = rng.normal(size=(length,) ).astype(np.floataa ) a = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Dict: '''simple docstring''' return self.length def __getitem__( self , A ) -> Union[str, Any]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class a__ ( torch.nn.Module ): def __init__( self , A=0 , A=0 , A=False ) -> Union[str, Any]: '''simple docstring''' super().__init__() a = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a = True def lowerCAmelCase_ ( self , A=None ) -> str: '''simple docstring''' if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) a = False return x * self.a[0] + self.b[0] class a__ ( torch.nn.Module ): def __init__( self , A=0 , A=0 , A=False ) -> List[Any]: '''simple docstring''' super().__init__() a = torch.nn.Parameter(torch.tensor(A ).float() ) a = torch.nn.Parameter(torch.tensor(A ).float() ) a = True def lowerCAmelCase_ ( self , A=None ) -> str: '''simple docstring''' if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) a = False return x * self.a + self.b def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase = 16) -> Tuple: from datasets import load_dataset from transformers import AutoTokenizer a = AutoTokenizer.from_pretrained("bert-base-cased") a = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} a = load_dataset("csv" , data_files=__UpperCamelCase) a = datasets["train"].unique("label") a = {v: i for i, v in enumerate(__UpperCamelCase)} def tokenize_function(__UpperCamelCase): # max_length=None => use the model max length (it's actually the default) a = tokenizer( examples["sentence1"] , examples["sentence2"] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding="max_length") if "label" in examples: a = [label_to_id[l] for l in examples["label"]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset a = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["sentence1", "sentence2", "label"] , ) def collate_fn(__UpperCamelCase): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__UpperCamelCase , padding="max_length" , max_length=1_28 , return_tensors="pt") return tokenizer.pad(__UpperCamelCase , padding="longest" , return_tensors="pt") # Instantiate dataloaders. a = DataLoader(tokenized_datasets["train"] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2) a = DataLoader(tokenized_datasets["validation"] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1) return train_dataloader, eval_dataloader
350
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase__ : int = logging.get_logger(__name__) lowercase__ : Dict = "▁" lowercase__ : Union[str, Any] = {"vocab_file": "spiece.model"} lowercase__ : Union[str, Any] = { "vocab_file": { "google/reformer-crime-and-punishment": ( "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" ) } } lowercase__ : Tuple = { "google/reformer-crime-and-punishment": 524_288, } class a__ ( UpperCamelCase__ ): a : List[Any] = VOCAB_FILES_NAMES a : List[Any] = PRETRAINED_VOCAB_FILES_MAP a : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Dict = ["""input_ids""", """attention_mask"""] def __init__( self , A , A="</s>" , A="<unk>" , A=[] , A = None , **A , ) -> None: '''simple docstring''' a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=A , unk_token=A , additional_special_tokens=A , sp_model_kwargs=self.sp_model_kwargs , **A , ) a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) @property def lowerCAmelCase_ ( self ) -> Optional[Any]: '''simple docstring''' return self.sp_model.get_piece_size() def lowerCAmelCase_ ( self ) -> Dict[str, int]: '''simple docstring''' a = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[int]: '''simple docstring''' a = self.__dict__.copy() a = None return state def __setstate__( self , A ) -> Union[str, Any]: '''simple docstring''' a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase_ ( self , A ) -> List[str]: '''simple docstring''' return self.sp_model.encode(A , out_type=A ) def lowerCAmelCase_ ( self , A ) -> Union[str, Any]: '''simple docstring''' return self.sp_model.piece_to_id(A ) def lowerCAmelCase_ ( self , A ) -> Optional[int]: '''simple docstring''' if index < self.sp_model.get_piece_size(): a = self.sp_model.IdToPiece(A ) return token def lowerCAmelCase_ ( self , A ) -> Union[str, Any]: '''simple docstring''' a = [] a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A ) + token a = [] else: current_sub_tokens.append(A ) out_string += self.sp_model.decode(A ) return out_string.strip() def lowerCAmelCase_ ( self , A , A = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return a = os.path.join( A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A ) elif not os.path.isfile(self.vocab_file ): with open(A , "wb" ) as fi: a = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
180
0
import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC __UpperCamelCase : Tuple = parse(importlib.metadata.version('torch')) def A ( _lowercase , _lowercase , _lowercase ): if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(f"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}""" ) SCREAMING_SNAKE_CASE : Optional[int] = STR_OPERATION_TO_FUNC[operation] if isinstance(_lowercase , _lowercase ): SCREAMING_SNAKE_CASE : List[str] = parse(importlib.metadata.version(_lowercase ) ) return operation(_lowercase , parse(_lowercase ) ) def A ( _lowercase , _lowercase ): return compare_versions(_lowercase , _lowercase , _lowercase )
182
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class lowercase__ ( unittest.TestCase): def __A ( self : str , UpperCamelCase__ : int ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(UpperCamelCase__ ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCamelCase__ , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = '''sgugger/tiny-distilbert-classification''' SCREAMING_SNAKE_CASE : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , only_pretrain_model=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : List[str] = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCamelCase__ , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = TensorFlowBenchmark(UpperCamelCase__ , [config] ) SCREAMING_SNAKE_CASE : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : List[str] = TensorFlowBenchmark(UpperCamelCase__ , [config] ) SCREAMING_SNAKE_CASE : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Optional[int] = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Dict = TensorFlowBenchmark(UpperCamelCase__ , [config] ) SCREAMING_SNAKE_CASE : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = '''patrickvonplaten/t5-tiny-random''' SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Dict = TensorFlowBenchmark(UpperCamelCase__ , configs=[config] ) SCREAMING_SNAKE_CASE : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , '''Cannot do xla on CPU.''' ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''sshleifer/tiny-gpt2''' SCREAMING_SNAKE_CASE : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase__ , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=UpperCamelCase__ , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Any = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCamelCase__ , save_to_csv=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(UpperCamelCase__ , '''inf_time.csv''' ) , inference_memory_csv_file=os.path.join(UpperCamelCase__ , '''inf_mem.csv''' ) , env_info_csv_file=os.path.join(UpperCamelCase__ , '''env.csv''' ) , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Optional[Any] = TensorFlowBenchmark(UpperCamelCase__ ) benchmark.run() self.assertTrue(Path(os.path.join(UpperCamelCase__ , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCamelCase__ , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCamelCase__ , '''env.csv''' ) ).exists() ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(UpperCamelCase__ : Dict ): self.assertTrue(hasattr(UpperCamelCase__ , '''sequential''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''cumulative''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''current''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCamelCase__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(UpperCamelCase__ , '''log.txt''' ) , log_print=UpperCamelCase__ , trace_memory_line_by_line=UpperCamelCase__ , eager_mode=UpperCamelCase__ , multi_process=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : List[Any] = TensorFlowBenchmark(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(UpperCamelCase__ , '''log.txt''' ) ).exists() )
182
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available lowercase__ ={ 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ =[ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ =['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys lowercase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
371
def __UpperCamelCase ( lowerCAmelCase__ : list ): def merge(lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(lowerCAmelCase__ ) <= 1: return collection __a : str = len(lowerCAmelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() lowercase__ =input('Enter numbers separated by a comma:\n').strip() lowercase__ =[int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',')
90
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''post_extract_proj''': '''feature_projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.upsample.0''': '''encoder.upsample.projection''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for attribute in key.split('''.''' ): snake_case_ = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if weight_type is not None: snake_case_ = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).shape else: snake_case_ = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value else: snake_case_ = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hf_model.config.feat_extract_norm == '''group''' , ) snake_case_ = True else: for key, mapped_key in MAPPING.items(): snake_case_ = '''sew.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(SCREAMING_SNAKE_CASE__ )[0].split('''.''' )[-2] snake_case_ = mapped_key.replace('''*''' , SCREAMING_SNAKE_CASE__ ) if "weight_g" in name: snake_case_ = '''weight_g''' elif "weight_v" in name: snake_case_ = '''weight_v''' elif "weight" in name: snake_case_ = '''weight''' elif "bias" in name: snake_case_ = '''bias''' else: snake_case_ = None set_recursively(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = full_name.split('''conv_layers.''' )[-1] snake_case_ = name.split('''.''' ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) snake_case_ = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) snake_case_ = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) snake_case_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) snake_case_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(SCREAMING_SNAKE_CASE__ ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ = SEWConfig() if is_finetuned: snake_case_ = model.wav_encoder.wav_model.cfg else: snake_case_ = model.cfg snake_case_ = fs_config.conv_bias snake_case_ = eval(fs_config.conv_feature_layers ) snake_case_ = [x[0] for x in conv_layers] snake_case_ = [x[1] for x in conv_layers] snake_case_ = [x[2] for x in conv_layers] snake_case_ = '''gelu''' snake_case_ = '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group''' snake_case_ = 0.0 snake_case_ = fs_config.activation_fn.name snake_case_ = fs_config.encoder_embed_dim snake_case_ = 0.02 snake_case_ = fs_config.encoder_ffn_embed_dim snake_case_ = 1E-5 snake_case_ = fs_config.encoder_layerdrop snake_case_ = fs_config.encoder_attention_heads snake_case_ = fs_config.conv_pos_groups snake_case_ = fs_config.conv_pos snake_case_ = len(SCREAMING_SNAKE_CASE__ ) snake_case_ = fs_config.encoder_layers snake_case_ = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: snake_case_ = model.cfg snake_case_ = fs_config.final_dropout snake_case_ = fs_config.layerdrop snake_case_ = fs_config.activation_dropout snake_case_ = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 snake_case_ = fs_config.attention_dropout snake_case_ = fs_config.dropout_input snake_case_ = fs_config.dropout snake_case_ = fs_config.mask_channel_length snake_case_ = fs_config.mask_channel_prob snake_case_ = fs_config.mask_length snake_case_ = fs_config.mask_prob snake_case_ = '''Wav2Vec2FeatureExtractor''' snake_case_ = '''Wav2Vec2CTCTokenizer''' return config @torch.no_grad() def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True ): if is_finetuned: snake_case_, snake_case_, snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: snake_case_, snake_case_, snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: snake_case_ = SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: snake_case_ = convert_config(model[0] , SCREAMING_SNAKE_CASE__ ) snake_case_ = model[0].eval() snake_case_ = True if config.feat_extract_norm == '''layer''' else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) if is_finetuned: if dict_path: snake_case_ = Dictionary.load(SCREAMING_SNAKE_CASE__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.json''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(SCREAMING_SNAKE_CASE__ ) ) return os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices , SCREAMING_SNAKE_CASE__ ) snake_case_ = WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=SCREAMING_SNAKE_CASE__ , ) snake_case_ = WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case_ = SEWForCTC(SCREAMING_SNAKE_CASE__ ) else: snake_case_ = SEWModel(SCREAMING_SNAKE_CASE__ ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) recursively_load_weights(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--is_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) lowerCAmelCase_ = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
8
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE_ : Dict = '\\n@inproceedings{popovic-2015-chrf,\n title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation",\n author = "Popovi{\'c}, Maja",\n booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation",\n month = sep,\n year = "2015",\n address = "Lisbon, Portugal",\n publisher = "Association for Computational Linguistics",\n url = "https://aclanthology.org/W15-3049",\n doi = "10.18653/v1/W15-3049",\n pages = "392--395",\n}\n@inproceedings{popovic-2017-chrf,\n title = "chr{F}++: words helping character n-grams",\n author = "Popovi{\'c}, Maja",\n booktitle = "Proceedings of the Second Conference on Machine Translation",\n month = sep,\n year = "2017",\n address = "Copenhagen, Denmark",\n publisher = "Association for Computational Linguistics",\n url = "https://aclanthology.org/W17-4770",\n doi = "10.18653/v1/W17-4770",\n pages = "612--618",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' SCREAMING_SNAKE_CASE_ : str = '\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n' SCREAMING_SNAKE_CASE_ : List[str] = '\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n \'score\' (float): The chrF (chrF++) score,\n \'char_order\' (int): The character n-gram order,\n \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n \'beta\' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]\n >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]\n >>> chrf = datasets.load_metric("chrf")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self: List[str] ): """simple docstring""" if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""] , reference_urls=[ """https://github.com/m-popovic/chrF""", ] , ) def UpperCamelCase ( self: List[Any] , UpperCamelCase: Union[str, Any] , UpperCamelCase: Optional[Any] , UpperCamelCase: int = CHRF.CHAR_ORDER , UpperCamelCase: int = CHRF.WORD_ORDER , UpperCamelCase: int = CHRF.BETA , UpperCamelCase: bool = False , UpperCamelCase: bool = False , UpperCamelCase: bool = False , ): """simple docstring""" A__ = len(references[0] ) if any(len(UpperCamelCase ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) A__ = [[refs[i] for refs in references] for i in range(UpperCamelCase )] A__ = CHRF(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) A__ = sb_chrf.corpus_score(UpperCamelCase , UpperCamelCase ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
335
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowercase (SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: for attribute in key.split('.' ): SCREAMING_SNAKE_CASE = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if weight_type is not None: SCREAMING_SNAKE_CASE = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).shape else: SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE = value elif weight_type == "bias": SCREAMING_SNAKE_CASE = value else: SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowercase (SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ) -> Dict: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = fairseq_model.state_dict() SCREAMING_SNAKE_CASE = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , hf_model.config.feat_extract_norm == 'group' , ) SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE = 'sew.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: SCREAMING_SNAKE_CASE = True if "*" in mapped_key: SCREAMING_SNAKE_CASE = name.split(SCREAMING_SNAKE_CASE_ )[0].split('.' )[-2] SCREAMING_SNAKE_CASE = mapped_key.replace('*' , SCREAMING_SNAKE_CASE_ ) if "weight_g" in name: SCREAMING_SNAKE_CASE = 'weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE = 'weight_v' elif "weight" in name: SCREAMING_SNAKE_CASE = 'weight' elif "bias" in name: SCREAMING_SNAKE_CASE = 'bias' else: SCREAMING_SNAKE_CASE = None set_recursively(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE_ ) logger.warning(F'Unused weights: {unused_weights}' ) def lowercase (SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[str]: SCREAMING_SNAKE_CASE = full_name.split('conv_layers.' )[-1] SCREAMING_SNAKE_CASE = name.split('.' ) SCREAMING_SNAKE_CASE = int(items[0] ) SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(SCREAMING_SNAKE_CASE_ ) def lowercase (SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE = SEWConfig() if is_finetuned: SCREAMING_SNAKE_CASE = model.wav_encoder.wav_model.cfg else: SCREAMING_SNAKE_CASE = model.cfg SCREAMING_SNAKE_CASE = fs_config.conv_bias SCREAMING_SNAKE_CASE = eval(fs_config.conv_feature_layers ) SCREAMING_SNAKE_CASE = [x[0] for x in conv_layers] SCREAMING_SNAKE_CASE = [x[1] for x in conv_layers] SCREAMING_SNAKE_CASE = [x[2] for x in conv_layers] SCREAMING_SNAKE_CASE = 'gelu' SCREAMING_SNAKE_CASE = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group' SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = fs_config.activation_fn.name SCREAMING_SNAKE_CASE = fs_config.encoder_embed_dim SCREAMING_SNAKE_CASE = 0.02 SCREAMING_SNAKE_CASE = fs_config.encoder_ffn_embed_dim SCREAMING_SNAKE_CASE = 1E-5 SCREAMING_SNAKE_CASE = fs_config.encoder_layerdrop SCREAMING_SNAKE_CASE = fs_config.encoder_attention_heads SCREAMING_SNAKE_CASE = fs_config.conv_pos_groups SCREAMING_SNAKE_CASE = fs_config.conv_pos SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = fs_config.encoder_layers SCREAMING_SNAKE_CASE = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: SCREAMING_SNAKE_CASE = model.cfg SCREAMING_SNAKE_CASE = fs_config.final_dropout SCREAMING_SNAKE_CASE = fs_config.layerdrop SCREAMING_SNAKE_CASE = fs_config.activation_dropout SCREAMING_SNAKE_CASE = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 SCREAMING_SNAKE_CASE = fs_config.attention_dropout SCREAMING_SNAKE_CASE = fs_config.dropout_input SCREAMING_SNAKE_CASE = fs_config.dropout SCREAMING_SNAKE_CASE = fs_config.mask_channel_length SCREAMING_SNAKE_CASE = fs_config.mask_channel_prob SCREAMING_SNAKE_CASE = fs_config.mask_length SCREAMING_SNAKE_CASE = fs_config.mask_prob SCREAMING_SNAKE_CASE = 'Wav2Vec2FeatureExtractor' SCREAMING_SNAKE_CASE = 'Wav2Vec2CTCTokenizer' return config @torch.no_grad() def lowercase (SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , SCREAMING_SNAKE_CASE_ : List[str]=True ) -> Any: if is_finetuned: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: SCREAMING_SNAKE_CASE = SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE = convert_config(model[0] , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = model[0].eval() SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == 'layer' else False SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ) if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE = Dictionary.load(SCREAMING_SNAKE_CASE_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE = target_dict.pad_index SCREAMING_SNAKE_CASE = target_dict.bos_index SCREAMING_SNAKE_CASE = target_dict.pad_index SCREAMING_SNAKE_CASE = target_dict.bos_index SCREAMING_SNAKE_CASE = target_dict.eos_index SCREAMING_SNAKE_CASE = len(target_dict.symbols ) SCREAMING_SNAKE_CASE = os.path.join(SCREAMING_SNAKE_CASE_ , 'vocab.json' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(SCREAMING_SNAKE_CASE_ ) ) return os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(target_dict.indices , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = SEWForCTC(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE = SEWModel(SCREAMING_SNAKE_CASE_ ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) recursively_load_weights(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--is_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __UpperCamelCase = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
352
"""simple docstring""" import operator as op def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> int: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = lambda SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(SCREAMING_SNAKE_CASE_ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(SCREAMING_SNAKE_CASE_ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) else: SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) SCREAMING_SNAKE_CASE = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' ) stack.append( str(opr[x](int(SCREAMING_SNAKE_CASE_ ) , int(SCREAMING_SNAKE_CASE_ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(SCREAMING_SNAKE_CASE_ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": __UpperCamelCase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
38
0
from __future__ import annotations import requests lowercase_ = set( "approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split() ) def _snake_case( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : str = "new" , SCREAMING_SNAKE_CASE__ : list | None = None ) -> dict: '''simple docstring''' A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(SCREAMING_SNAKE_CASE__ ) - valid_terms ) ): A__ = f'Invalid search term: {invalid_search_terms}' raise ValueError(SCREAMING_SNAKE_CASE__ ) A__ = requests.get( f'https://reddit.com/r/{subreddit}/{age}.json?limit={limit}' , headers={'User-agent': 'A random string'} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(SCREAMING_SNAKE_CASE__ )} A__ = {} for id_ in range(SCREAMING_SNAKE_CASE__ ): A__ = { item: data['data']['children'][id_]['data'][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
7
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def _SCREAMING_SNAKE_CASE ( _lowercase : int ) ->str: '''simple docstring''' if not isinstance(_lowercase , _lowercase ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) a : Tuple = precision a : str = ceil(precision / 14 ) a : List[Any] = 42_6880 * Decimal(1_0005 ).sqrt() a : Union[str, Any] = 1 a : Dict = 1359_1409 a : Optional[int] = Decimal(_lowercase ) for k in range(1 , _lowercase ): a : int = factorial(6 * k ) // (factorial(3 * k ) * factorial(_lowercase ) ** 3) linear_term += 5_4514_0134 exponential_term *= -26_2537_4126_4076_8000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a : Optional[Any] = 50 print(F'''The first {n} digits of pi is: {pi(n)}''')
105
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : List[Any]=224 , UpperCAmelCase_ : Tuple=30 , UpperCAmelCase_ : Union[str, Any]=400 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=[0.5, 0.5, 0.5] , UpperCAmelCase_ : Optional[int]=[0.5, 0.5, 0.5] , ) ->Union[str, Any]: """simple docstring""" snake_case_ = size if size is not None else {'''height''': 18, '''width''': 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize snake_case_ = image_mean snake_case_ = image_std def lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __A (a__ , unittest.TestCase): '''simple docstring''' __lowercase: List[str] = ViTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = EfficientFormerImageProcessorTester(self ) @property def lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """size""" ) ) def lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" pass def lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input snake_case_ = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched snake_case_ = image_processor(_lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input snake_case_ = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched snake_case_ = image_processor(_lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input snake_case_ = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched snake_case_ = image_processor(_lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
354
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "\n".join( f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
233
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor __lowercase : Optional[int] = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , *__a , **__a ): '''simple docstring''' warnings.warn( 'The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DeiTImageProcessor instead.' , __a , ) super().__init__(*__a , **__a )
27
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __snake_case = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' __snake_case = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' __snake_case = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def A_ ( _lowerCAmelCase : List[str] ): """simple docstring""" def remove_articles(_lowerCAmelCase : Optional[int] ): _a = re.compile(R'''\b(a|an|the)\b''', re.UNICODE ) return re.sub(_lowerCAmelCase, ''' ''', _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase : Tuple ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase : Tuple ): _a = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase : List[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase : List[Any], _lowerCAmelCase : Optional[Any] ): """simple docstring""" return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase : Tuple, _lowerCAmelCase : Any ): """simple docstring""" _a = [any(compute_exact(_lowerCAmelCase, _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase, _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 1_00 def A_ ( _lowerCAmelCase : List[str], _lowerCAmelCase : List[Any], _lowerCAmelCase : str, _lowerCAmelCase : str ): """simple docstring""" _a = [rgram for rgrams in rgramslist for rgram in rgrams] _a = Counter(_lowerCAmelCase ) _a = Counter(_lowerCAmelCase ) _a = Counter() for sgram, scount in sgramcounter.items(): _a = scount * numref _a = Counter(_lowerCAmelCase ) _a = Counter() for cgram, ccount in cgramcounter.items(): _a = ccount * numref # KEEP _a = sgramcounter_rep & cgramcounter_rep _a = keepgramcounter_rep & rgramcounter _a = sgramcounter_rep & rgramcounter _a = 0 _a = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _a = 1 _a = 1 if len(_lowerCAmelCase ) > 0: _a = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) _a = keeptmpscorea / sum(keepgramcounterall_rep.values() ) _a = 0 if keepscore_precision > 0 or keepscore_recall > 0: _a = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION _a = sgramcounter_rep - cgramcounter_rep _a = delgramcounter_rep - rgramcounter _a = sgramcounter_rep - rgramcounter _a = 0 _a = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _a = 1 if len(_lowerCAmelCase ) > 0: _a = deltmpscorea / len(_lowerCAmelCase ) # ADDITION _a = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) _a = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) _a = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) _a = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _a = 1 _a = 1 if len(_lowerCAmelCase ) > 0: _a = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: _a = addtmpscore / len(_lowerCAmelCase ) _a = 0 if addscore_precision > 0 or addscore_recall > 0: _a = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase : Tuple, _lowerCAmelCase : Dict, _lowerCAmelCase : Any ): """simple docstring""" _a = len(_lowerCAmelCase ) _a = ssent.split(''' ''' ) _a = csent.split(''' ''' ) _a = [] _a = [] _a = [] _a = [] _a = [] _a = [] _a = [] _a = [] _a = [] _a = [] for rsent in rsents: _a = rsent.split(''' ''' ) _a = [] _a = [] _a = [] ragramslist.append(_lowerCAmelCase ) for i in range(0, len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: _a = ragrams[i] + ''' ''' + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: _a = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: _a = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] + ''' ''' + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0, len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: _a = sagrams[i] + ''' ''' + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: _a = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: _a = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] + ''' ''' + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0, len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: _a = cagrams[i] + ''' ''' + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: _a = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: _a = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] + ''' ''' + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((_a) , (_a) , (_a)) = SARIngram(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) ((_a) , (_a) , (_a)) = SARIngram(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) ((_a) , (_a) , (_a)) = SARIngram(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) ((_a) , (_a) , (_a)) = SARIngram(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) _a = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 _a = sum([delascore, delascore, delascore, delascore] ) / 4 _a = sum([addascore, addascore, addascore, addascore] ) / 4 _a = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase : str, _lowerCAmelCase : bool = True, _lowerCAmelCase : str = "13a", _lowerCAmelCase : bool = True ): """simple docstring""" if lowercase: _a = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: _a = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: _a = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": _a = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase, return_str=_lowerCAmelCase, escape=_lowerCAmelCase ) elif tokenizer == "penn": _a = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase, return_str=_lowerCAmelCase ) else: _a = sentence if not return_str: _a = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase : List[Any], _lowerCAmelCase : Dict, _lowerCAmelCase : Optional[Any] ): """simple docstring""" if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError('''Sources length must match predictions and references lengths.''' ) _a = 0 for src, pred, refs in zip(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ), normalize(_lowerCAmelCase ), [normalize(_lowerCAmelCase ) for sent in refs] ) _a = sari_score / len(_lowerCAmelCase ) return 1_00 * sari_score def A_ ( _lowerCAmelCase : Tuple, _lowerCAmelCase : Tuple, _lowerCAmelCase : Any="exp", _lowerCAmelCase : Tuple=None, _lowerCAmelCase : Union[str, Any]=False, _lowerCAmelCase : Optional[Any]=False, _lowerCAmelCase : List[str]=False, ): """simple docstring""" _a = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) _a = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] _a = sacrebleu.corpus_bleu( _lowerCAmelCase, _lowerCAmelCase, smooth_method=_lowerCAmelCase, smooth_value=_lowerCAmelCase, force=_lowerCAmelCase, lowercase=_lowerCAmelCase, use_effective_order=_lowerCAmelCase, ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCamelCase ( datasets.Metric ): '''simple docstring''' def _UpperCAmelCase ( self ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=[ '''https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py''', '''https://github.com/cocoxu/simplification/blob/master/SARI.py''', '''https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py''', '''https://github.com/mjpost/sacreBLEU''', ] , reference_urls=[ '''https://www.aclweb.org/anthology/Q16-1029.pdf''', '''https://github.com/mjpost/sacreBLEU''', '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> str: _a = {} result.update({'''sari''': compute_sari(sources=__UpperCAmelCase , predictions=__UpperCAmelCase , references=__UpperCAmelCase )} ) result.update({'''sacrebleu''': compute_sacrebleu(predictions=__UpperCAmelCase , references=__UpperCAmelCase )} ) result.update({'''exact''': compute_em(predictions=__UpperCAmelCase , references=__UpperCAmelCase )} ) return result
320
0
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class snake_case__(unittest.TestCase ): """simple docstring""" def __init__( self : str , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[Any]=13 , SCREAMING_SNAKE_CASE : Optional[int]=7 , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : Dict=True , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : int=True , SCREAMING_SNAKE_CASE : Dict=99 , SCREAMING_SNAKE_CASE : int=32 , SCREAMING_SNAKE_CASE : int=5 , SCREAMING_SNAKE_CASE : Optional[int]=4 , SCREAMING_SNAKE_CASE : Any=37 , SCREAMING_SNAKE_CASE : Dict="gelu" , SCREAMING_SNAKE_CASE : List[str]=0.1 , SCREAMING_SNAKE_CASE : List[str]=0.1 , SCREAMING_SNAKE_CASE : Optional[Any]=512 , SCREAMING_SNAKE_CASE : str=16 , SCREAMING_SNAKE_CASE : str=2 , SCREAMING_SNAKE_CASE : int=0.02 , SCREAMING_SNAKE_CASE : Union[str, Any]=4 , ): lowercase__ : Optional[Any] = parent lowercase__ : List[Any] = batch_size lowercase__ : List[Any] = seq_length lowercase__ : List[str] = is_training lowercase__ : int = use_attention_mask lowercase__ : Optional[int] = use_token_type_ids lowercase__ : Dict = use_labels lowercase__ : Tuple = vocab_size lowercase__ : Union[str, Any] = hidden_size lowercase__ : Dict = num_hidden_layers lowercase__ : List[str] = num_attention_heads lowercase__ : str = intermediate_size lowercase__ : List[str] = hidden_act lowercase__ : str = hidden_dropout_prob lowercase__ : Optional[Any] = attention_probs_dropout_prob lowercase__ : Union[str, Any] = max_position_embeddings lowercase__ : int = type_vocab_size lowercase__ : List[str] = type_sequence_label_size lowercase__ : List[Any] = initializer_range lowercase__ : List[Any] = num_choices def snake_case ( self : Optional[Any] ): lowercase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : List[str] = None if self.use_attention_mask: lowercase__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ : Union[str, Any] = None if self.use_token_type_ids: lowercase__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def snake_case ( self : str ): lowercase__ : List[str] = self.prepare_config_and_inputs() lowercase__ : str = config_and_inputs lowercase__ : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class snake_case__(_UpperCamelCase , unittest.TestCase ): """simple docstring""" lowercase_ = True lowercase_ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def snake_case ( self : str ): lowercase__ : int = FlaxRoFormerModelTester(self ) @slow def snake_case ( self : Tuple ): for model_class_name in self.all_model_classes: lowercase__ : Tuple = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=SCREAMING_SNAKE_CASE ) lowercase__ : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_flax class snake_case__(unittest.TestCase ): """simple docstring""" @slow def snake_case ( self : Any ): lowercase__ : List[Any] = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) lowercase__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) lowercase__ : Tuple = model(SCREAMING_SNAKE_CASE )[0] lowercase__ : Optional[int] = 50_000 lowercase__ : int = (1, 6, vocab_size) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) lowercase__ : int = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
368
def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : Union[str, Any] = [] lowercase__ : Tuple = [] lowercase__ : Any = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator lowercase__ : Any = len(lowerCamelCase__ ) if (len(lowerCamelCase__ ) > 7) else 7 # Print table header for output print( "Symbol".center(8 ) , "Stack".center(lowerCamelCase__ ) , "Postfix".center(lowerCamelCase__ ) , sep=" | " , ) print("-" * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(lowerCamelCase__ ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(lowerCamelCase__ ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(lowerCamelCase__ ) == 0: stack.append(lowerCamelCase__ ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(lowerCamelCase__ ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(lowerCamelCase__ ) # push x to stack print( x.center(8 ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , sep=" | " , ) # Output in tabular format while len(lowerCamelCase__ ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( " ".center(8 ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , ("".join(lowerCamelCase__ )).ljust(lowerCamelCase__ ) , sep=" | " , ) # Output in tabular format return "".join(lowerCamelCase__ ) # return Postfix as str def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : Optional[int] = list(infix[::-1] ) # reverse the infix equation for i in range(len(lowerCamelCase__ ) ): if infix[i] == "(": lowercase__ : Tuple = ")" # change "(" to ")" elif infix[i] == ")": lowercase__ : Optional[Any] = "(" # change ")" to "(" return (infix_2_postfix("".join(lowerCamelCase__ ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": lowerCAmelCase__ = input('''\nEnter an Infix Equation = ''') # Input an Infix equation lowerCAmelCase__ = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
121
0
"""simple docstring""" from typing import Any import numpy as np def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> List[Any]: return np.array_equal(lowerCAmelCase__ , matrix.conjugate().T ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: lowercase__: Optional[Any] = v.conjugate().T lowercase__: Optional[int] = v_star.dot(lowerCAmelCase__ ) assert isinstance(lowerCAmelCase__ , np.ndarray ) return (v_star_dot.dot(lowerCAmelCase__ )) / (v_star.dot(lowerCAmelCase__ )) def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: lowercase__: Optional[Any] = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) lowercase__: int = np.array([[1], [2], [3]] ) assert is_hermitian(lowerCAmelCase__ ), F"""{a} is not hermitian.""" print(rayleigh_quotient(lowerCAmelCase__ , lowerCAmelCase__ ) ) lowercase__: Optional[Any] = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowerCAmelCase__ ), F"""{a} is not hermitian.""" assert rayleigh_quotient(lowerCAmelCase__ , lowerCAmelCase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
177
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class UpperCamelCase__ : _SCREAMING_SNAKE_CASE : Union[str, Any] = LEDConfig _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : int = "gelu" def __init__(self : List[str] , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any]=1_3 , snake_case_ : Optional[Any]=7 , snake_case_ : Any=True , snake_case_ : List[Any]=False , snake_case_ : str=9_9 , snake_case_ : Any=3_2 , snake_case_ : Dict=2 , snake_case_ : List[Any]=4 , snake_case_ : Optional[int]=3_7 , snake_case_ : Dict=0.1 , snake_case_ : int=0.1 , snake_case_ : Optional[Any]=2_0 , snake_case_ : Optional[Any]=2 , snake_case_ : Optional[int]=1 , snake_case_ : Optional[int]=0 , snake_case_ : str=4 , ): __a : List[Any] = parent __a : Union[str, Any] = batch_size __a : List[str] = seq_length __a : Any = is_training __a : Tuple = use_labels __a : List[Any] = vocab_size __a : Optional[Any] = hidden_size __a : int = num_hidden_layers __a : Optional[int] = num_attention_heads __a : int = intermediate_size __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : int = max_position_embeddings __a : Tuple = eos_token_id __a : Optional[Any] = pad_token_id __a : List[str] = bos_token_id __a : List[str] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after __a : Union[str, Any] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests __a : List[str] = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def lowerCAmelCase (self : Optional[int] ): __a : Dict = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __a : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __a : int = tf.concat([input_ids, eos_tensor] , axis=1 ) __a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Optional[int] = 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 , attention_window=self.attention_window , **self.config_updates , ) __a : Optional[int] = prepare_led_inputs_dict(snake_case_ , snake_case_ , snake_case_ ) __a : Dict = tf.concat( [tf.zeros_like(snake_case_ )[:, :-1], tf.ones_like(snake_case_ )[:, -1:]] , axis=-1 , ) __a : Tuple = global_attention_mask return config, inputs_dict def lowerCAmelCase (self : List[Any] , snake_case_ : Dict , snake_case_ : int ): __a : List[str] = TFLEDModel(config=snake_case_ ).get_decoder() __a : Dict = inputs_dict['''input_ids'''] __a : Dict = input_ids[:1, :] __a : Any = inputs_dict['''attention_mask'''][:1, :] __a : List[str] = 1 # first forward pass __a : Optional[Any] = model(snake_case_ , attention_mask=snake_case_ , use_cache=snake_case_ ) __a , __a : Tuple = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __a : str = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __a : Optional[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) __a : Optional[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __a : Optional[int] = model(snake_case_ , attention_mask=snake_case_ )[0] __a : int = model(snake_case_ , attention_mask=snake_case_ , past_key_values=snake_case_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __a : Any = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __a : List[Any] = output_from_no_past[:, -3:, random_slice_idx] __a : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(snake_case_ , snake_case_ , rtol=1E-3 ) def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]=None , lowerCAmelCase__ : int=None , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=None , ): if attention_mask is None: __a : Any = tf.cast(tf.math.not_equal(lowerCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __a : Dict = 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: __a : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a : str = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class UpperCamelCase__ ( __lowercase ,__lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _SCREAMING_SNAKE_CASE : Tuple = (TFLEDForConditionalGeneration,) if is_tf_available() else () _SCREAMING_SNAKE_CASE : Optional[Any] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def lowerCAmelCase (self : Optional[int] ): __a : List[str] = TFLEDModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=snake_case_ ) def lowerCAmelCase (self : Any ): self.config_tester.run_common_tests() def lowerCAmelCase (self : Optional[Any] ): __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*snake_case_ ) def lowerCAmelCase (self : Any ): __a , __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __a : Any = tf.zeros_like(inputs_dict['''attention_mask'''] ) __a : Tuple = 2 __a : Dict = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) __a : List[str] = True __a : Tuple = self.model_tester.seq_length __a : Any = self.model_tester.encoder_seq_length def check_decoder_attentions_output(snake_case_ : Any ): __a : str = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(snake_case_ : Optional[int] ): __a : int = [t.numpy() for t in outputs.encoder_attentions] __a : int = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: __a : Dict = True __a : Optional[Any] = False __a : List[str] = False __a : List[Any] = model_class(snake_case_ ) __a : List[str] = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) __a : List[str] = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: __a : List[str] = model_class(snake_case_ ) __a : int = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __a : List[Any] = True __a : Dict = model_class(snake_case_ ) __a : Tuple = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine __a : List[str] = True __a : Any = True __a : Tuple = model_class(snake_case_ ) __a : int = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def lowerCAmelCase (self : List[str] ): pass def lowerCAmelCase (self : List[Any] ): # TODO: Head-masking not yet implement pass def __UpperCamelCase ( lowerCAmelCase__ : Optional[Any] ): return tf.constant(lowerCAmelCase__ , dtype=tf.intaa ) lowercase__ =1e-4 @slow @require_tf class UpperCamelCase__ ( unittest.TestCase ): def lowerCAmelCase (self : Any ): __a : Dict = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here __a : Union[str, Any] = _long_tensor([5_1_2 * [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]] ) __a : Dict = _long_tensor([1_2_8 * [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]] ) __a : List[str] = prepare_led_inputs_dict(model.config , snake_case_ , snake_case_ ) __a : List[str] = model(**snake_case_ )[0] __a : Any = (1, 1_0_2_4, 7_6_8) self.assertEqual(output.shape , snake_case_ ) # change to expected output here __a : Dict = tf.convert_to_tensor( [[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-3 ) def lowerCAmelCase (self : int ): __a : Optional[Any] = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here __a : int = _long_tensor([5_1_2 * [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]] ) __a : Tuple = _long_tensor([1_2_8 * [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]] ) __a : Dict = prepare_led_inputs_dict(model.config , snake_case_ , snake_case_ ) __a : List[str] = model(**snake_case_ )[0] __a : List[Any] = (1, 1_0_2_4, model.config.vocab_size) self.assertEqual(output.shape , snake_case_ ) # change to expected output here __a : str = tf.convert_to_tensor( [[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-3 , rtol=1E-3 )
216
0
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> float: def get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) -> str: _a : Any = [] _a : List[str] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): _a : Dict = int(max(0 , i - limit ) ) _a : str = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) _a : List[Any] = f"""{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}""" return "".join(lowerCAmelCase_ ) # matching characters _a : int = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) _a : List[str] = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) _a : Optional[int] = len(lowerCAmelCase_ ) # transposition _a : Optional[Any] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: _a : List[Any] = 0.0 else: _a : int = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters _a : str = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('''hello''', '''world'''))
107
'''simple docstring''' # Function to print upper half of diamond (pyramid) def __lowerCamelCase ( lowerCAmelCase_ ) -> int: 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 __lowerCamelCase ( lowerCAmelCase_ ) -> Union[str, Any]: 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 __lowerCamelCase ( 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'''|/ \| |- |_ |_ |__| | \/ | |_''') __lowerCAmelCase = 1 while K: __lowerCAmelCase = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) __lowerCAmelCase = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
107
1
# Copyright 2022 The HuggingFace Team and The OpenBMB 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCAmelCase : Optional[int] = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : List[str] = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
300
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def __lowercase ( lowerCamelCase : str , lowerCamelCase : str , **lowerCamelCase : List[Any] ): UpperCamelCase_ : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase_ : str = AutoModelForSeqaSeqLM.from_config(lowerCamelCase ) model.save_pretrained(lowerCamelCase ) AutoTokenizer.from_pretrained(lowerCamelCase ).save_pretrained(lowerCamelCase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
175
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a__ = logging.get_logger(__name__) a__ = { '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class UpperCAmelCase_ ( A__ , A__ ): """simple docstring""" UpperCAmelCase__ : List[str] = "focalnet" def __init__( self , _a=2_2_4 , _a=4 , _a=3 , _a=9_6 , _a=False , _a=[1_9_2, 3_8_4, 7_6_8, 7_6_8] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1e-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1e-5 , _a=3_2 , _a=None , _a=None , **_a , ) -> List[Any]: super().__init__(**__A ) _a : List[str] = image_size _a : str = patch_size _a : Optional[Any] = num_channels _a : Dict = embed_dim _a : Dict = use_conv_embed _a : List[str] = hidden_sizes _a : List[Any] = depths _a : Tuple = focal_levels _a : Union[str, Any] = focal_windows _a : Any = hidden_act _a : Dict = mlp_ratio _a : Tuple = hidden_dropout_prob _a : str = drop_path_rate _a : Dict = use_layerscale _a : Optional[int] = layerscale_value _a : int = use_post_layernorm _a : int = use_post_layernorm_in_modulation _a : List[Any] = normalize_modulator _a : str = initializer_range _a : int = layer_norm_eps _a : Tuple = encoder_stride _a : str = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] _a : Optional[Any] = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
351
from math import ceil def __UpperCAmelCase ( __a : int = 1_001 ) -> int: """simple docstring""" _a : Dict = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): _a : int = 2 * i + 1 _a : str = 2 * i _a : Any = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: a__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
15
0
"""simple docstring""" def __lowerCAmelCase ( lowercase : list[list[int]] , lowercase : int , lowercase : int , lowercase : set ) -> int: """simple docstring""" snake_case ,snake_case : int = len(lowercase ), len(grid[0] ) if ( min(lowercase , lowercase ) < 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) ) snake_case : Optional[int] = 0 count += depth_first_search(lowercase , row + 1 , lowercase , lowercase ) count += depth_first_search(lowercase , row - 1 , lowercase , lowercase ) count += depth_first_search(lowercase , lowercase , col + 1 , lowercase ) count += depth_first_search(lowercase , lowercase , col - 1 , lowercase ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
203
"""simple docstring""" def __lowerCAmelCase ( lowercase : List[str] , lowercase : Union[str, Any] , lowercase : List[str] , lowercase : Tuple , lowercase : List[Any] , lowercase : int ) -> List[Any]: """simple docstring""" if index == r: for j in range(lowercase ): print(data[j] , end=" " ) print(" " ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location snake_case : Union[str, Any] = arr[i] combination_util(lowercase , lowercase , lowercase , index + 1 , lowercase , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowercase , lowercase , lowercase , lowercase , lowercase , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def __lowerCAmelCase ( lowercase : Any , lowercase : Union[str, Any] , lowercase : Optional[int] ) -> List[Any]: """simple docstring""" snake_case : Any = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowercase , lowercase , lowercase , 0 , lowercase , 0 ) if __name__ == "__main__": # Driver code to check the function above __snake_case = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
203
1
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __snake_case :Union[str, Any] = '''platform''' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , ): if attention_mask is None: __a = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __a = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __a = np.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": attention_mask, } class _A : def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Any=13 , __SCREAMING_SNAKE_CASE : List[Any]=7 , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : Tuple=False , __SCREAMING_SNAKE_CASE : str=99 , __SCREAMING_SNAKE_CASE : Any=16 , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : str="gelu" , __SCREAMING_SNAKE_CASE : Optional[int]=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.1 , __SCREAMING_SNAKE_CASE : Any=32 , __SCREAMING_SNAKE_CASE : Dict=2 , __SCREAMING_SNAKE_CASE : Any=1 , __SCREAMING_SNAKE_CASE : Optional[int]=0 , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , ): '''simple docstring''' __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = eos_token_id __a = pad_token_id __a = bos_token_id __a = initializer_range def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) , 3 , self.vocab_size) __a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa)) , -1) __a = shift_tokens_right(__SCREAMING_SNAKE_CASE , 1 , 2) __a = BlenderbotConfig( 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=__SCREAMING_SNAKE_CASE , ) __a = prepare_blenderbot_inputs_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) return config, inputs_dict def _lowerCamelCase ( self : int): '''simple docstring''' __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any]): '''simple docstring''' __a = 20 __a = model_class_name(__SCREAMING_SNAKE_CASE) __a = model.encode(inputs_dict['''input_ids''']) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = model.init_cache(decoder_input_ids.shape[0] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''') __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , __SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE , decoder_position_ids=__SCREAMING_SNAKE_CASE , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''') __a = model.decode( decoder_input_ids[:, -1:] , __SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__SCREAMING_SNAKE_CASE , ) __a = model.decode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1E-3 , msg=F'Max diff is {diff}') def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any]): '''simple docstring''' __a = 20 __a = model_class_name(__SCREAMING_SNAKE_CASE) __a = model.encode(inputs_dict['''input_ids''']) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])), ] , axis=-1 , ) __a = model.init_cache(decoder_input_ids.shape[0] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , __SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE , decoder_position_ids=__SCREAMING_SNAKE_CASE , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''') __a = model.decode( decoder_input_ids[:, -1:] , __SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__SCREAMING_SNAKE_CASE , decoder_position_ids=__SCREAMING_SNAKE_CASE , ) __a = model.decode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1E-3 , msg=F'Max diff is {diff}') @require_flax class _A ( unittest.TestCase ): UpperCamelCase__ : Dict = 99 def _lowerCamelCase ( self : int): '''simple docstring''' __a = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __a = input_ids.shape[0] __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_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 def _lowerCamelCase ( self : Optional[Any]): '''simple docstring''' __a , __a , __a = self._get_config_and_data() __a = FlaxBlenderbotForConditionalGeneration(__SCREAMING_SNAKE_CASE) __a = lm_model(input_ids=__SCREAMING_SNAKE_CASE) __a = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : str): '''simple docstring''' __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __a = FlaxBlenderbotForConditionalGeneration(__SCREAMING_SNAKE_CASE) __a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa) __a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa) __a = lm_model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE) __a = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : List[str]): '''simple docstring''' __a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa) __a = shift_tokens_right(__SCREAMING_SNAKE_CASE , 1 , 2) __a = np.equal(__SCREAMING_SNAKE_CASE , 1).astype(np.floataa).sum() __a = np.equal(__SCREAMING_SNAKE_CASE , 1).astype(np.floataa).sum() self.assertEqual(shifted.shape , input_ids.shape) self.assertEqual(__SCREAMING_SNAKE_CASE , n_pad_before - 1) self.assertTrue(np.equal(shifted[:, 0] , 2).all()) @require_flax class _A ( __UpperCAmelCase ,unittest.TestCase ,__UpperCAmelCase ): UpperCamelCase__ : Optional[Any] = True UpperCamelCase__ : Optional[int] = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) UpperCamelCase__ : List[Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a = FlaxBlenderbotModelTester(self) def _lowerCamelCase ( self : str): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : List[str]): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): __a = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = model_class(__SCREAMING_SNAKE_CASE) @jax.jit def encode_jitted(__SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]=None , **__SCREAMING_SNAKE_CASE : List[Any]): return model.encode(input_ids=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE) with self.subTest('''JIT Enabled'''): __a = encode_jitted(**__SCREAMING_SNAKE_CASE).to_tuple() with self.subTest('''JIT Disabled'''): with jax.disable_jit(): __a = encode_jitted(**__SCREAMING_SNAKE_CASE).to_tuple() self.assertEqual(len(__SCREAMING_SNAKE_CASE) , len(__SCREAMING_SNAKE_CASE)) for jitted_output, output in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): self.assertEqual(jitted_output.shape , output.shape) def _lowerCamelCase ( self : Any): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): __a = model_class(__SCREAMING_SNAKE_CASE) __a = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask''']) __a = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(__SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any): return model.decode( decoder_input_ids=__SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE , encoder_outputs=__SCREAMING_SNAKE_CASE , ) with self.subTest('''JIT Enabled'''): __a = decode_jitted(**__SCREAMING_SNAKE_CASE).to_tuple() with self.subTest('''JIT Disabled'''): with jax.disable_jit(): __a = decode_jitted(**__SCREAMING_SNAKE_CASE).to_tuple() self.assertEqual(len(__SCREAMING_SNAKE_CASE) , len(__SCREAMING_SNAKE_CASE)) for jitted_output, output in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): self.assertEqual(jitted_output.shape , output.shape) @slow def _lowerCamelCase ( self : Any): '''simple docstring''' for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''') # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __a = np.ones((1, 1)) * model.config.eos_token_id __a = model(__SCREAMING_SNAKE_CASE) self.assertIsNotNone(__SCREAMING_SNAKE_CASE) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''') @slow def _lowerCamelCase ( self : Dict): '''simple docstring''' __a = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} __a = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} __a = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=__SCREAMING_SNAKE_CASE) __a = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''') __a = ['''Sam'''] __a = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''jax''') __a = model.generate(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = '''Sam is a great name. It means "sun" in Gaelic.''' __a = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) assert generated_txt[0].strip() == tgt_text
131
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case :Dict = logging.get_logger(__name__) __snake_case :List[Any] = { '''tanreinama/GPTSAN-2.8B-spout_is_uniform''': ( '''https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json''' ), } class _A ( __UpperCAmelCase ): UpperCamelCase__ : List[str] = '''gptsan-japanese''' UpperCamelCase__ : Dict = [ '''past_key_values''', ] UpperCamelCase__ : Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any]=36_000 , __SCREAMING_SNAKE_CASE : Tuple=1_280 , __SCREAMING_SNAKE_CASE : List[Any]=1_024 , __SCREAMING_SNAKE_CASE : List[Any]=8_192 , __SCREAMING_SNAKE_CASE : str=4_096 , __SCREAMING_SNAKE_CASE : Any=128 , __SCREAMING_SNAKE_CASE : int=10 , __SCREAMING_SNAKE_CASE : Optional[int]=0 , __SCREAMING_SNAKE_CASE : Optional[Any]=16 , __SCREAMING_SNAKE_CASE : List[Any]=16 , __SCREAMING_SNAKE_CASE : Optional[Any]=128 , __SCREAMING_SNAKE_CASE : Tuple=0.0 , __SCREAMING_SNAKE_CASE : List[Any]=1E-5 , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.0 , __SCREAMING_SNAKE_CASE : List[str]="float32" , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : int=0.0_02 , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : int=35_998 , __SCREAMING_SNAKE_CASE : Optional[int]=35_995 , __SCREAMING_SNAKE_CASE : List[str]=35_999 , **__SCREAMING_SNAKE_CASE : List[str] , ): '''simple docstring''' __a = vocab_size __a = max_position_embeddings __a = d_model __a = d_ff __a = d_ext __a = d_spout __a = num_switch_layers __a = num_ext_layers __a = num_switch_layers + num_ext_layers __a = num_heads __a = num_experts __a = expert_capacity __a = dropout_rate __a = layer_norm_epsilon __a = router_bias __a = router_jitter_noise __a = router_dtype __a = router_ignore_padding_tokens __a = output_hidden_states __a = output_attentions __a = initializer_factor __a = output_router_logits __a = use_cache super().__init__( separator_token_id=__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , )
131
1
'''simple docstring''' import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) class A__ ( A__ ): A__ = ['input_ids', 'attention_mask'] def __init__( self : Any , _a : List[str]="</s>" , _a : Optional[int]="<unk>" , _a : Optional[Any]="<pad>" , _a : Optional[int]=125 , _a : Optional[Any]=None , **_a : Optional[Any] , ) -> None: '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: _SCREAMING_SNAKE_CASE =[f"<extra_id_{i}>" for i in range(_a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens _SCREAMING_SNAKE_CASE =len(set(filter(lambda _a : bool('extra_id' in str(_a ) ) , _a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the' ' extra_ids tokens' ) _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token super().__init__( eos_token=_a , unk_token=_a , pad_token=_a , extra_ids=_a , additional_special_tokens=_a , **_a , ) _SCREAMING_SNAKE_CASE =extra_ids _SCREAMING_SNAKE_CASE =2**8 # utf is 8 bits # define special tokens dict _SCREAMING_SNAKE_CASE ={ self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } _SCREAMING_SNAKE_CASE =len(self.special_tokens_encoder ) _SCREAMING_SNAKE_CASE =len(_a ) for i, token in enumerate(_a ): _SCREAMING_SNAKE_CASE =self.vocab_size + i - n _SCREAMING_SNAKE_CASE ={v: k for k, v in self.special_tokens_encoder.items()} @property def A ( self : str ) -> Dict: '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def A ( self : str , _a : List[int] , _a : Optional[List[int]] = None , _a : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_a )) + [1] return ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] def A ( self : str , _a : List[int] ) -> List[int]: '''simple docstring''' if len(_a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def A ( self : Union[str, Any] , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def A ( self : Optional[int] , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._add_eos_if_not_present(_a ) if token_ids_a is None: return token_ids_a else: _SCREAMING_SNAKE_CASE =self._add_eos_if_not_present(_a ) return token_ids_a + token_ids_a def A ( self : List[Any] , _a : str ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[chr(_a ) for i in text.encode('utf-8' )] return tokens def A ( self : List[Any] , _a : List[Any] ) -> List[Any]: '''simple docstring''' if token in self.special_tokens_encoder: _SCREAMING_SNAKE_CASE =self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: _SCREAMING_SNAKE_CASE =self.added_tokens_encoder[token] elif len(_a ) != 1: _SCREAMING_SNAKE_CASE =self.unk_token_id else: _SCREAMING_SNAKE_CASE =ord(_a ) + self._num_special_tokens return token_id def A ( self : Tuple , _a : Optional[int] ) -> str: '''simple docstring''' if index in self.special_tokens_decoder: _SCREAMING_SNAKE_CASE =self.special_tokens_decoder[index] else: _SCREAMING_SNAKE_CASE =chr(index - self._num_special_tokens ) return token def A ( self : int , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =b'' for token in tokens: if token in self.special_tokens_decoder: _SCREAMING_SNAKE_CASE =self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.added_tokens_decoder: _SCREAMING_SNAKE_CASE =self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.special_tokens_encoder: _SCREAMING_SNAKE_CASE =token.encode('utf-8' ) elif token in self.added_tokens_encoder: _SCREAMING_SNAKE_CASE =token.encode('utf-8' ) else: _SCREAMING_SNAKE_CASE =bytes([ord(_a )] ) bstring += tok_string _SCREAMING_SNAKE_CASE =bstring.decode('utf-8' , errors='ignore' ) return string def A ( self : int , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' return ()
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
371
'''simple docstring''' import os import re 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 _snake_case : str = logging.get_logger(__name__) _snake_case : Tuple = {'vocab_file': 'spiece.model'} _snake_case : Optional[int] = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } _snake_case : Tuple = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class A ( _a ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = ['input_ids', 'attention_mask'] lowercase_ = [] def __init__( self : Optional[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[int]="<unk>" , lowerCAmelCase_ : Tuple="<s>" , lowerCAmelCase_ : List[str]="</s>" , lowerCAmelCase_ : int="<pad>" , lowerCAmelCase_ : Union[str, Any]="[SEP]" , lowerCAmelCase_ : Dict="[MASK]" , lowerCAmelCase_ : Optional[int]="[CLS]" , lowerCAmelCase_ : Optional[Dict[str, Any]] = None , **lowerCAmelCase_ : Union[str, Any] , ) -> None: """simple docstring""" _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else bos_token _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else eos_token _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else unk_token _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else pad_token _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else cls_token _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it _a = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else mask_token _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase_ , ) _a = vocab_file _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase_ ) @property def __lowerCAmelCase ( self : Union[str, Any] ) -> int: """simple docstring""" return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : str ) -> List[str]: """simple docstring""" _a = {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 : str ) -> Tuple: """simple docstring""" _a = self.__dict__.copy() _a = None return state def __setstate__( self : List[str] , lowerCAmelCase_ : Any ) -> Dict: """simple docstring""" _a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _a = {} _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(lowerCAmelCase_ , out_type=lowerCAmelCase_ ) def __lowerCAmelCase ( self : str , lowerCAmelCase_ : List[str] ) -> int: """simple docstring""" return self.sp_model.piece_to_id(lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : Tuple ) -> str: """simple docstring""" _a = self.sp_model.IdToPiece(lowerCAmelCase_ ) return token def __lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" _a = [] _a = '''''' _a = 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 _a = True _a = [] else: current_sub_tokens.append(lowerCAmelCase_ ) _a = False out_string += self.sp_model.decode(lowerCAmelCase_ ) return out_string.strip() def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = None , lowerCAmelCase_ : bool = True , **lowerCAmelCase_ : Tuple , ) -> str: """simple docstring""" _a = kwargs.pop('''use_source_tokenizer''' , lowerCAmelCase_ ) _a = self.convert_ids_to_tokens(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 _a = [] _a = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowerCAmelCase_ ) ) _a = [] sub_texts.append(lowerCAmelCase_ ) else: current_sub_text.append(lowerCAmelCase_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowerCAmelCase_ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: _a = re.sub(R''' (\[(MASK|SEP)\])''' , R'''\1''' , ''' '''.join(lowerCAmelCase_ ) ) else: _a = ''''''.join(lowerCAmelCase_ ) _a = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: _a = self.clean_up_tokenization(lowerCAmelCase_ ) return clean_text else: return text def __lowerCAmelCase ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return _a = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) 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: _a = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase_ ) return (out_vocab_file,) def __lowerCAmelCase ( self : int , 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] _a = [self.cls_token_id] _a = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , 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=lowerCAmelCase_ , token_ids_a=lowerCAmelCase_ , already_has_special_tokens=lowerCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCAmelCase_ )) + [1] return [1] + ([0] * len(lowerCAmelCase_ )) + [1] + ([0] * len(lowerCAmelCase_ )) + [1] def __lowerCAmelCase ( self : Tuple , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" _a = [self.sep_token_id] _a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
179
0
from __future__ import annotations def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = sorted(numsa + numsa ) lowercase , lowercase = divmod(len(lowerCAmelCase__ ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() lowercase__ :List[Any] = [float(x) for x in input("Enter the elements of first array: ").split()] lowercase__ :List[str] = [float(x) for x in input("Enter the elements of second array: ").split()] print(F'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
101
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowercase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase_ : Tuple =ShapEPipeline lowercase_ : List[Any] =['''prompt'''] lowercase_ : int =['''prompt'''] lowercase_ : Union[str, Any] =[ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] lowercase_ : Optional[int] =False @property def A__ ( self): return 3_2 @property def A__ ( self): return 3_2 @property def A__ ( self): return self.time_input_dim * 4 @property def A__ ( self): return 8 @property def A__ ( self): lowercase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') return tokenizer @property def A__ ( self): torch.manual_seed(0) lowercase = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=self.text_embedder_hidden_size ,projection_dim=self.text_embedder_hidden_size ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,) return CLIPTextModelWithProjection(A__) @property def A__ ( self): torch.manual_seed(0) lowercase = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_6, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 3_2, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase = PriorTransformer(**A__) return model @property def A__ ( self): torch.manual_seed(0) lowercase = { '''param_shapes''': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 1_2, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase = ShapERenderer(**A__) return model def A__ ( self): lowercase = self.dummy_prior lowercase = self.dummy_text_encoder lowercase = self.dummy_tokenizer lowercase = self.dummy_renderer lowercase = HeunDiscreteScheduler( beta_schedule='''exp''' ,num_train_timesteps=1_0_2_4 ,prediction_type='''sample''' ,use_karras_sigmas=A__ ,clip_sample=A__ ,clip_sample_range=1.0 ,) lowercase = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def A__ ( self ,A__ ,A__=0): if str(A__).startswith('''mps'''): lowercase = torch.manual_seed(A__) else: lowercase = torch.Generator(device=A__).manual_seed(A__) lowercase = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 3_2, '''output_type''': '''np''', } return inputs def A__ ( self): lowercase = '''cpu''' lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = pipe(**self.get_dummy_inputs(A__)) lowercase = output.images[0] lowercase = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) lowercase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def A__ ( self): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2]) def A__ ( self): lowercase = torch_device == '''cpu''' lowercase = True self._test_inference_batch_single_identical( batch_size=2 ,test_max_difference=A__ ,relax_max_difference=A__ ,) def A__ ( self): lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = 1 lowercase = 2 lowercase = self.get_dummy_inputs(A__) for key in inputs.keys(): if key in self.batch_params: lowercase = batch_size * [inputs[key]] lowercase = pipe(**A__ ,num_images_per_prompt=A__)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def A__ ( self): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self): lowercase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''') lowercase = ShapEPipeline.from_pretrained('''openai/shap-e''') lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = torch.Generator(device=A__).manual_seed(0) lowercase = pipe( '''a shark''' ,generator=A__ ,guidance_scale=15.0 ,num_inference_steps=6_4 ,frame_size=6_4 ,output_type='''np''' ,).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(A__ ,A__)
101
1
'''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 A_ : def __init__( self : List[str] , snake_case_ : Dict , snake_case_ : Union[str, Any]=1_3 , snake_case_ : Dict=3_0 , snake_case_ : Tuple=2 , snake_case_ : List[Any]=3 , snake_case_ : int=True , snake_case_ : int=True , snake_case_ : Any=3_2 , snake_case_ : Optional[Any]=2 , snake_case_ : Tuple=4 , snake_case_ : Dict=3_7 , snake_case_ : List[str]="gelu" , snake_case_ : Optional[Any]=0.1 , snake_case_ : Union[str, Any]=0.1 , snake_case_ : int=1_0 , snake_case_ : Optional[Any]=0.0_2 , snake_case_ : Dict=3 , snake_case_ : Optional[int]=None , snake_case_ : Optional[Any]=2 , ): _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = is_training _UpperCAmelCase = use_labels _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 = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = scope _UpperCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) _UpperCAmelCase = (image_size // patch_size) ** 2 _UpperCAmelCase = num_patches + 2 def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def lowercase ( self : Optional[Any] ): 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 : List[str] , snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : str ): _UpperCAmelCase = TFDeiTModel(config=snake_case_ ) _UpperCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase ( self : Any , snake_case_ : Optional[int] , snake_case_ : List[Any] , snake_case_ : str ): _UpperCAmelCase = TFDeiTForMaskedImageModeling(config=snake_case_ ) _UpperCAmelCase = model(snake_case_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _UpperCAmelCase = 1 _UpperCAmelCase = TFDeiTForMaskedImageModeling(snake_case_ ) _UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _UpperCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase ( self : Union[str, Any] , snake_case_ : str , snake_case_ : Tuple , snake_case_ : Tuple ): _UpperCAmelCase = self.type_sequence_label_size _UpperCAmelCase = TFDeiTForImageClassification(snake_case_ ) _UpperCAmelCase = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _UpperCAmelCase = 1 _UpperCAmelCase = TFDeiTForImageClassification(snake_case_ ) _UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _UpperCAmelCase = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowercase ( self : Any ): _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class A_ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : Tuple = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _lowerCamelCase : Optional[int] = ( { """feature-extraction""": TFDeiTModel, """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _lowerCamelCase : str = False _lowerCamelCase : List[Any] = False _lowerCamelCase : List[Any] = False _lowerCamelCase : Optional[int] = False def lowercase ( self : Optional[int] ): _UpperCAmelCase = TFDeiTModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=3_7 ) def lowercase ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def lowercase ( self : Tuple ): pass def lowercase ( self : List[str] ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(snake_case_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case_ , tf.keras.layers.Dense ) ) def lowercase ( self : str ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(snake_case_ ) _UpperCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case_ ) def lowercase ( self : List[str] ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def lowercase ( self : int ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_ ) def lowercase ( self : List[str] ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) def lowercase ( self : Union[str, Any] , snake_case_ : Optional[Any] , snake_case_ : Dict , snake_case_ : Any=False ): _UpperCAmelCase = 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 : List[str] ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = TFDeiTModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def UpperCAmelCase_ ( ) -> Any: '''simple docstring''' _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowercase ( self : Any ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def lowercase ( self : Any ): _UpperCAmelCase = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=snake_case_ , return_tensors="tf" ) # forward pass _UpperCAmelCase = model(**snake_case_ ) # verify the logits _UpperCAmelCase = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , snake_case_ ) _UpperCAmelCase = tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , snake_case_ , atol=1e-4 ) )
156
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE :Dict = '''▁''' __SCREAMING_SNAKE_CASE :List[str] = { '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } __SCREAMING_SNAKE_CASE :Tuple = { '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } __SCREAMING_SNAKE_CASE :Optional[int] = { '''facebook/m2m100_418M''': 1024, } # fmt: off __SCREAMING_SNAKE_CASE :Dict = { '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class A_ ( lowerCAmelCase_ ): _lowerCamelCase : List[str] = VOCAB_FILES_NAMES _lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : List[str] = ["""input_ids""", """attention_mask"""] _lowerCamelCase : List[int] = [] _lowerCamelCase : List[int] = [] def __init__( self : List[str] , snake_case_ : Any , snake_case_ : List[Any] , snake_case_ : str=None , snake_case_ : int=None , snake_case_ : str="<s>" , snake_case_ : int="</s>" , snake_case_ : Any="</s>" , snake_case_ : List[str]="<pad>" , snake_case_ : Optional[int]="<unk>" , snake_case_ : Union[str, Any]="m2m100" , snake_case_ : Optional[Dict[str, Any]] = None , snake_case_ : List[str]=8 , **snake_case_ : str , ): _UpperCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs _UpperCAmelCase = language_codes _UpperCAmelCase = FAIRSEQ_LANGUAGE_CODES[language_codes] _UpperCAmelCase = {lang_code: f'__{lang_code}__' for lang_code in fairseq_language_code} _UpperCAmelCase = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(snake_case_ ) for lang_code in fairseq_language_code if self.get_lang_token(snake_case_ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=snake_case_ , tgt_lang=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , sep_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , language_codes=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=snake_case_ , **snake_case_ , ) _UpperCAmelCase = vocab_file _UpperCAmelCase = load_json(snake_case_ ) _UpperCAmelCase = {v: k for k, v in self.encoder.items()} _UpperCAmelCase = spm_file _UpperCAmelCase = load_spm(snake_case_ , self.sp_model_kwargs ) _UpperCAmelCase = len(self.encoder ) _UpperCAmelCase = { self.get_lang_token(snake_case_ ): self.encoder_size + i for i, lang_code in enumerate(snake_case_ ) } _UpperCAmelCase = {lang_code: self.encoder_size + i for i, lang_code in enumerate(snake_case_ )} _UpperCAmelCase = {v: k for k, v in self.lang_token_to_id.items()} _UpperCAmelCase = src_lang if src_lang is not None else "en" _UpperCAmelCase = tgt_lang _UpperCAmelCase = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) _UpperCAmelCase = num_madeup_words @property def lowercase ( self : int ): return len(self.encoder ) + len(self.lang_token_to_id ) @property def lowercase ( self : List[Any] ): return self._src_lang @src_lang.setter def lowercase ( self : str , snake_case_ : str ): _UpperCAmelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowercase ( self : str , snake_case_ : str ): return self.sp_model.encode(snake_case_ , out_type=snake_case_ ) def lowercase ( self : Optional[Any] , snake_case_ : int ): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(snake_case_ , self.encoder[self.unk_token] ) def lowercase ( self : Any , snake_case_ : int ): if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(snake_case_ , self.unk_token ) def lowercase ( self : List[str] , snake_case_ : List[str] ): _UpperCAmelCase = [] _UpperCAmelCase = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(snake_case_ ) + token _UpperCAmelCase = [] else: current_sub_tokens.append(snake_case_ ) out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def lowercase ( self : str , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None , snake_case_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) _UpperCAmelCase = [1] * len(self.prefix_tokens ) _UpperCAmelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(snake_case_ )) + suffix_ones return prefix_ones + ([0] * len(snake_case_ )) + ([0] * len(snake_case_ )) + suffix_ones def lowercase ( self : Optional[int] , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowercase ( self : Dict ): _UpperCAmelCase = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ): _UpperCAmelCase = self.__dict__.copy() _UpperCAmelCase = None return state def __setstate__( self : List[str] , snake_case_ : Dict ): _UpperCAmelCase = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _UpperCAmelCase = {} _UpperCAmelCase = load_spm(self.spm_file , self.sp_model_kwargs ) def lowercase ( self : int , snake_case_ : str , snake_case_ : Optional[str] = None ): _UpperCAmelCase = Path(snake_case_ ) if not save_dir.is_dir(): raise OSError(f'{save_directory} should be a directory' ) _UpperCAmelCase = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _UpperCAmelCase = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , snake_case_ ) if os.path.abspath(self.spm_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , snake_case_ ) elif not os.path.isfile(self.spm_file ): with open(snake_case_ , "wb" ) as fi: _UpperCAmelCase = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (str(snake_case_ ), str(snake_case_ )) def lowercase ( self : Dict , snake_case_ : List[str] , snake_case_ : str = "en" , snake_case_ : Optional[List[str]] = None , snake_case_ : str = "ro" , **snake_case_ : Any , ): _UpperCAmelCase = src_lang _UpperCAmelCase = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(snake_case_ , snake_case_ , **snake_case_ ) def lowercase ( self : Tuple , snake_case_ : Optional[Any] , snake_case_ : Optional[str] , snake_case_ : Optional[str] , **snake_case_ : Any ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) _UpperCAmelCase = src_lang _UpperCAmelCase = self(snake_case_ , add_special_tokens=snake_case_ , **snake_case_ ) _UpperCAmelCase = self.get_lang_id(snake_case_ ) _UpperCAmelCase = tgt_lang_id return inputs def lowercase ( self : List[str] ): self.set_src_lang_special_tokens(self.src_lang ) def lowercase ( self : Optional[Any] ): self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowercase ( self : Any , snake_case_ : str ): _UpperCAmelCase = self.get_lang_token(snake_case_ ) _UpperCAmelCase = self.lang_token_to_id[lang_token] _UpperCAmelCase = [self.cur_lang_id] _UpperCAmelCase = [self.eos_token_id] def lowercase ( self : List[Any] , snake_case_ : str ): _UpperCAmelCase = self.get_lang_token(snake_case_ ) _UpperCAmelCase = self.lang_token_to_id[lang_token] _UpperCAmelCase = [self.cur_lang_id] _UpperCAmelCase = [self.eos_token_id] def lowercase ( self : Tuple , snake_case_ : str ): return self.lang_code_to_token[lang] def lowercase ( self : List[str] , snake_case_ : str ): _UpperCAmelCase = self.get_lang_token(snake_case_ ) return self.lang_token_to_id[lang_token] def UpperCAmelCase_ ( __lowercase : str , __lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: '''simple docstring''' _UpperCAmelCase = sentencepiece.SentencePieceProcessor(**__lowercase ) spm.Load(str(__lowercase ) ) return spm def UpperCAmelCase_ ( __lowercase : str ) -> Union[Dict, List]: '''simple docstring''' with open(__lowercase , "r" ) as f: return json.load(__lowercase ) def UpperCAmelCase_ ( __lowercase : str , __lowercase : str ) -> None: '''simple docstring''' with open(__lowercase , "w" ) as f: json.dump(__lowercase , __lowercase , indent=2 )
156
1
"""simple docstring""" from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __snake_case : Dict = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Any , **_SCREAMING_SNAKE_CASE: int) -> Any: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__( self: Tuple , _SCREAMING_SNAKE_CASE: Union[str, List[str], "Image", List["Image"]] , **_SCREAMING_SNAKE_CASE: str) -> List[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[int] , **_SCREAMING_SNAKE_CASE: List[str]) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : str = {} if "candidate_labels" in kwargs: __lowerCAmelCase : List[Any] = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __lowerCAmelCase : int = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: Optional[Any]="This is a photo of {}.") -> List[str]: """simple docstring""" __lowerCAmelCase : Any = load_image(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = self.image_processor(images=[image] , return_tensors=self.framework) __lowerCAmelCase : List[str] = candidate_labels __lowerCAmelCase : Tuple = [hypothesis_template.format(_SCREAMING_SNAKE_CASE) for x in candidate_labels] __lowerCAmelCase : Tuple = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = [text_inputs] return inputs def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: Tuple) -> List[Any]: """simple docstring""" __lowerCAmelCase : int = model_inputs.pop("candidate_labels") __lowerCAmelCase : List[str] = model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : Tuple = text_inputs[0] else: # Batching case. __lowerCAmelCase : Tuple = text_inputs[0][0] __lowerCAmelCase : Optional[Any] = self.model(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) __lowerCAmelCase : int = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_image, } return model_outputs def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]) -> int: """simple docstring""" __lowerCAmelCase : int = model_outputs.pop("candidate_labels") __lowerCAmelCase : Optional[Any] = model_outputs['''logits'''][0] if self.framework == "pt": __lowerCAmelCase : Optional[Any] = logits.softmax(dim=-1).squeeze(-1) __lowerCAmelCase : List[str] = probs.tolist() if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : Optional[Any] = [scores] elif self.framework == "tf": __lowerCAmelCase : Union[str, Any] = stable_softmax(_SCREAMING_SNAKE_CASE , axis=-1) __lowerCAmelCase : Optional[Any] = probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") __lowerCAmelCase : List[str] = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) , key=lambda _SCREAMING_SNAKE_CASE: -x[0]) ] return result
269
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : def __init__( self : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int]=13 , __magic_name__ : str=7 , __magic_name__ : Dict=True , __magic_name__ : Dict=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : Tuple=99 , __magic_name__ : List[str]=32 , __magic_name__ : int=2 , __magic_name__ : List[str]=4 , __magic_name__ : Tuple=37 , __magic_name__ : Dict="gelu" , __magic_name__ : int=0.1 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : Optional[int]=5_12 , __magic_name__ : Tuple=16 , __magic_name__ : Optional[int]=2 , __magic_name__ : Optional[int]=0.0_2 , __magic_name__ : Dict=3 , __magic_name__ : str=4 , __magic_name__ : Optional[Any]=None , __magic_name__ : Any=0 , ) -> Any: """simple docstring""" UpperCAmelCase_ : str = parent UpperCAmelCase_ : List[Any] = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : Optional[Any] = use_input_mask UpperCAmelCase_ : Tuple = use_token_type_ids UpperCAmelCase_ : int = use_labels UpperCAmelCase_ : Union[str, Any] = vocab_size UpperCAmelCase_ : Union[str, Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : Any = num_attention_heads UpperCAmelCase_ : Any = intermediate_size UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : Tuple = hidden_dropout_prob UpperCAmelCase_ : List[Any] = attention_probs_dropout_prob UpperCAmelCase_ : str = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : List[str] = type_sequence_label_size UpperCAmelCase_ : Tuple = initializer_range UpperCAmelCase_ : str = num_labels UpperCAmelCase_ : Tuple = num_choices UpperCAmelCase_ : Union[str, Any] = scope UpperCAmelCase_ : Union[str, Any] = projection_dim def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Dict = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py UpperCAmelCase_ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : Tuple = None if self.use_token_type_ids: UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : int = None if self.use_labels: UpperCAmelCase_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : Optional[Any] = BertConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) UpperCAmelCase_ : List[str] = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : str , __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : List[str] , __magic_name__ : List[str] , __magic_name__ : Tuple , __magic_name__ : Any ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = TFDPRContextEncoder(config=__magic_name__ ) UpperCAmelCase_ : Tuple = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : int = model(__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : int , __magic_name__ : Dict , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : Tuple ) -> int: """simple docstring""" UpperCAmelCase_ : List[str] = TFDPRQuestionEncoder(config=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : Tuple , __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = TFDPRReader(config=__magic_name__ ) UpperCAmelCase_ : Tuple = model(__magic_name__ , attention_mask=__magic_name__ ) 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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Any = {'''input_ids''': input_ids} return config, inputs_dict @require_tf class __a (lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Any = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) __a : int = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {} __a : str = False __a : str = False __a : Dict = False __a : Optional[Any] = False __a : Any = False def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Optional[int] = TFDPRModelTester(self ) UpperCAmelCase_ : Dict = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__magic_name__ ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Union[str, Any] = TFDPRContextEncoder.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[Any] = TFDPRContextEncoder.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Tuple = TFDPRQuestionEncoder.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Tuple = TFDPRReader.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_tf class __a (unittest.TestCase ): @slow def UpperCAmelCase__ ( self : Optional[int] ) -> str: """simple docstring""" UpperCAmelCase_ : Any = TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base''' ) UpperCAmelCase_ : Optional[int] = tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] UpperCAmelCase_ : List[Any] = model(__magic_name__ )[0] # embedding shape = (1, 768) # compare the actual values for a slice. UpperCAmelCase_ : List[str] = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
125
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = (DPMSolverSinglestepScheduler,) a_ = (("num_inference_steps", 2_5),) def _lowercase ( self : Dict , **__A : int ): snake_case__ : int = { "num_train_timesteps": 1_0_0_0, "beta_start": 0.0_0_0_1, "beta_end": 0.0_2, "beta_schedule": "linear", "solver_order": 2, "prediction_type": "epsilon", "thresholding": False, "sample_max_value": 1.0, "algorithm_type": "dpmsolver++", "solver_type": "midpoint", "lambda_min_clipped": -float("inf" ), "variance_type": None, } config.update(**__A ) return config def _lowercase ( self : str , __A : Optional[int]=0 , **__A : Optional[Any] ): snake_case__ : Dict = dict(self.forward_default_kwargs ) snake_case__ : Dict = kwargs.pop("num_inference_steps" , __A ) snake_case__ : Optional[Any] = self.dummy_sample snake_case__ : str = 0.1 * sample snake_case__ : Dict = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: snake_case__ : Tuple = self.get_scheduler_config(**__A ) snake_case__ : Optional[int] = scheduler_class(**__A ) scheduler.set_timesteps(__A ) # copy over dummy past residuals snake_case__ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__A ) snake_case__ : int = scheduler_class.from_pretrained(__A ) new_scheduler.set_timesteps(__A ) # copy over dummy past residuals snake_case__ : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case__, snake_case__ : Any = sample, sample for t in range(__A , time_step + scheduler.config.solver_order + 1 ): snake_case__ : str = scheduler.step(__A , __A , __A , **__A ).prev_sample snake_case__ : List[Any] = new_scheduler.step(__A , __A , __A , **__A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowercase ( self : List[str] ): pass def _lowercase ( self : str , __A : Union[str, Any]=0 , **__A : Union[str, Any] ): snake_case__ : str = dict(self.forward_default_kwargs ) snake_case__ : int = kwargs.pop("num_inference_steps" , __A ) snake_case__ : List[str] = self.dummy_sample snake_case__ : Any = 0.1 * sample snake_case__ : int = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: snake_case__ : List[str] = self.get_scheduler_config() snake_case__ : Any = scheduler_class(**__A ) scheduler.set_timesteps(__A ) # copy over dummy past residuals (must be after setting timesteps) snake_case__ : Dict = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__A ) snake_case__ : str = scheduler_class.from_pretrained(__A ) # copy over dummy past residuals new_scheduler.set_timesteps(__A ) # copy over dummy past residual (must be after setting timesteps) snake_case__ : Any = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case__ : List[Any] = scheduler.step(__A , __A , __A , **__A ).prev_sample snake_case__ : List[Any] = new_scheduler.step(__A , __A , __A , **__A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowercase ( self : Union[str, Any] , __A : List[Any]=None , **__A : Union[str, Any] ): if scheduler is None: snake_case__ : str = self.scheduler_classes[0] snake_case__ : Union[str, Any] = self.get_scheduler_config(**__A ) snake_case__ : str = scheduler_class(**__A ) snake_case__ : Any = self.scheduler_classes[0] snake_case__ : Any = self.get_scheduler_config(**__A ) snake_case__ : str = scheduler_class(**__A ) snake_case__ : int = 1_0 snake_case__ : Union[str, Any] = self.dummy_model() snake_case__ : int = self.dummy_sample_deter scheduler.set_timesteps(__A ) for i, t in enumerate(scheduler.timesteps ): snake_case__ : int = model(__A , __A ) snake_case__ : int = scheduler.step(__A , __A , __A ).prev_sample return sample def _lowercase ( self : List[str] ): snake_case__ : Optional[int] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) snake_case__ : Tuple = 5_0 snake_case__ : Optional[int] = self.dummy_model() snake_case__ : Optional[Any] = self.dummy_sample_deter scheduler.set_timesteps(__A ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): snake_case__ : int = model(__A , __A ) snake_case__ : Any = scheduler.step(__A , __A , __A ).prev_sample snake_case__ : str = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.2_5_7_4 ) < 1e-3 def _lowercase ( self : str ): for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__A ) def _lowercase ( self : Tuple ): # make sure that iterating over schedulers with same config names gives same results # for defaults snake_case__ : List[Any] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) snake_case__ : Any = self.full_loop(scheduler=__A ) snake_case__ : Any = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 snake_case__ : Any = DEISMultistepScheduler.from_config(scheduler.config ) snake_case__ : Any = DPMSolverMultistepScheduler.from_config(scheduler.config ) snake_case__ : Tuple = UniPCMultistepScheduler.from_config(scheduler.config ) snake_case__ : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) snake_case__ : Tuple = self.full_loop(scheduler=__A ) snake_case__ : Union[str, Any] = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 def _lowercase ( self : List[str] ): self.check_over_configs(thresholding=__A ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , algorithm_type="dpmsolver++" , solver_order=__A , solver_type=__A , ) def _lowercase ( self : Dict ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def _lowercase ( self : List[str] ): for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__A , solver_type=__A , prediction_type=__A , algorithm_type=__A , ) snake_case__ : Dict = self.full_loop( solver_order=__A , solver_type=__A , prediction_type=__A , algorithm_type=__A , ) assert not torch.isnan(__A ).any(), "Samples have nan numbers" def _lowercase ( self : int ): self.check_over_configs(lower_order_final=__A ) self.check_over_configs(lower_order_final=__A ) def _lowercase ( self : str ): self.check_over_configs(lambda_min_clipped=-float("inf" ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def _lowercase ( self : Optional[Any] ): self.check_over_configs(variance_type=__A ) self.check_over_configs(variance_type="learned_range" ) def _lowercase ( self : Optional[Any] ): for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=__A , time_step=0 ) def _lowercase ( self : Any ): snake_case__ : int = self.full_loop() snake_case__ : Optional[Any] = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 def _lowercase ( self : str ): snake_case__ : int = self.full_loop(use_karras_sigmas=__A ) snake_case__ : List[str] = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.2_2_4_8 ) < 1e-3 def _lowercase ( self : List[Any] ): snake_case__ : Union[str, Any] = self.full_loop(prediction_type="v_prediction" ) snake_case__ : int = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.1_4_5_3 ) < 1e-3 def _lowercase ( self : List[Any] ): snake_case__ : Dict = self.full_loop(prediction_type="v_prediction" , use_karras_sigmas=__A ) snake_case__ : Dict = torch.mean(torch.abs(__A ) ) assert abs(result_mean.item() - 0.0_6_4_9 ) < 1e-3 def _lowercase ( self : Tuple ): snake_case__ : Optional[int] = self.scheduler_classes[0] snake_case__ : Union[str, Any] = self.get_scheduler_config(thresholding=__A , dynamic_thresholding_ratio=0 ) snake_case__ : int = scheduler_class(**__A ) snake_case__ : str = 1_0 snake_case__ : Optional[int] = self.dummy_model() snake_case__ : str = self.dummy_sample_deter.half() scheduler.set_timesteps(__A ) for i, t in enumerate(scheduler.timesteps ): snake_case__ : List[Any] = model(__A , __A ) snake_case__ : List[Any] = scheduler.step(__A , __A , __A ).prev_sample assert sample.dtype == torch.floataa
286
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" a_ = PhobertTokenizer a_ = False def _lowercase ( self : List[str] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : Optional[int] = ["T@@", "i", "I", "R@@", "r", "e@@"] snake_case__ : int = dict(zip(__A , range(len(__A ) ) ) ) snake_case__ : Dict = ["#version: 0.2", "l à</w>"] snake_case__ : Optional[Any] = {"unk_token": "<unk>"} snake_case__ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case__ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'''{token} {vocab_tokens[token]}\n''' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__A ) ) def _lowercase ( self : List[str] , **__A : Any ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__A ) def _lowercase ( self : Tuple , __A : List[Any] ): snake_case__ : str = "Tôi là VinAI Research" snake_case__ : int = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def _lowercase ( self : Optional[int] ): snake_case__ : int = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case__ : Tuple = "Tôi là VinAI Research" snake_case__ : List[Any] = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() snake_case__ : int = tokenizer.tokenize(__A ) print(__A ) self.assertListEqual(__A , __A ) snake_case__ : Any = tokens + [tokenizer.unk_token] snake_case__ : Any = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
286
1
'''simple docstring''' # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _UpperCamelCase = float('nan') class lowerCamelCase_ : """simple docstring""" def __init__( self : Tuple , _a : int ) -> Dict: __lowerCamelCase : Optional[Any] = sys.stdout __lowerCamelCase : str = open(_a , 'a' ) def __getattr__( self : Dict , _a : List[str] ) -> Optional[Any]: return getattr(self.stdout , _a ) def _lowercase ( self : Dict , _a : str ) -> Optional[int]: self.stdout.write(_a ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' , '' , _a , 0 , re.M ) ) def a_ ( _lowerCAmelCase=80 ,_lowerCAmelCase=False ) -> int: __lowerCamelCase : str = [] # deal with critical env vars __lowerCamelCase : Union[str, Any] = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: __lowerCamelCase : List[str] = os.environ.get(_lowerCAmelCase ,_lowerCAmelCase ) if val is not None: cmd.append(F'{key}={val}' ) # python executable (not always needed if the script is executable) __lowerCamelCase : str = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(_lowerCAmelCase ) # now the normal args cmd += list(map(shlex.quote ,sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = '' while len(_lowerCAmelCase ) > 0: current_line += F'{cmd.pop(0 )} ' if len(_lowerCAmelCase ) == 0 or len(_lowerCAmelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_lowerCAmelCase ) __lowerCamelCase : str = '' return "\\\n".join(_lowerCAmelCase ) def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> List[Any]: # unwrap multi-line input __lowerCamelCase : Optional[int] = re.sub(r'[\\\n]+' ,' ' ,args.base_cmd ) # remove --output_dir if any and set our own __lowerCamelCase : List[Any] = re.sub('--output_dir\s+[^\s]+' ,'' ,args.base_cmd ) args.base_cmd += F' --output_dir {output_dir}' # ensure we have --overwrite_output_dir __lowerCamelCase : List[Any] = re.sub('--overwrite_output_dir\s+' ,'' ,args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> int: # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 ,100 ) for k in metric_keys} ,**{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} ,) __lowerCamelCase : List[str] = subprocess.run(_lowerCAmelCase ,capture_output=_lowerCAmelCase ,text=_lowerCAmelCase ) if verbose: print('STDOUT' ,result.stdout ) print('STDERR' ,result.stderr ) # save the streams __lowerCamelCase : Union[str, Any] = variation.replace(' ' ,'-' ) with open(Path(_lowerCAmelCase ) / F'log.{prefix}.stdout.txt' ,'w' ) as f: f.write(result.stdout ) with open(Path(_lowerCAmelCase ) / F'log.{prefix}.stderr.txt' ,'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'{output_dir}/all_results.json' ,'r' ,encoding='utf-8' ) as f: __lowerCamelCase : Any = json.load(_lowerCAmelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,) -> Any: __lowerCamelCase : Optional[int] = [] __lowerCamelCase : Tuple = [] __lowerCamelCase : List[str] = F'{id}: {variation:<{longest_variation_len}}' __lowerCamelCase : List[Any] = F'{preamble}: ' __lowerCamelCase : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_lowerCAmelCase ) ,desc=_lowerCAmelCase ,leave=_lowerCAmelCase ): __lowerCamelCase : Optional[int] = process_run_single( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) __lowerCamelCase : int = single_run_metrics[target_metric_key] if not math.isnan(_lowerCAmelCase ): metrics.append(_lowerCAmelCase ) results.append(_lowerCAmelCase ) outcome += "✓" else: outcome += "✘" __lowerCamelCase : Optional[int] = F'\33[2K\r{outcome}' if len(_lowerCAmelCase ) > 0: __lowerCamelCase : Optional[int] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} __lowerCamelCase : Dict = round(mean_metrics[target_metric_key] ,2 ) __lowerCamelCase : str = F'{outcome} {mean_target}' if len(_lowerCAmelCase ) > 1: results_str += F' {tuple(round(_lowerCAmelCase ,2 ) for x in results )}' print(_lowerCAmelCase ) __lowerCamelCase : Union[str, Any] = variation return mean_metrics else: print(_lowerCAmelCase ) return {variation_key: variation, target_metric_key: nan} def a_ ( ) -> List[str]: __lowerCamelCase : str = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> Union[str, Any]: __lowerCamelCase : Optional[int] = pd.DataFrame(_lowerCAmelCase ) __lowerCamelCase : Dict = 'variation' __lowerCamelCase : Tuple = 'diff_%' __lowerCamelCase : Dict = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan __lowerCamelCase : List[str] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_lowerCAmelCase ): # as a fallback, use the minimal value as the sentinel __lowerCamelCase : List[str] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_lowerCAmelCase ): __lowerCamelCase : Dict = df.apply( lambda _lowerCAmelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 ,axis='columns' ,) # re-order columns __lowerCamelCase : Any = [variation_key, target_metric_key, diff_key, *report_metric_keys] __lowerCamelCase : Any = df.reindex(_lowerCAmelCase ,axis='columns' ) # reorder cols # capitalize __lowerCamelCase : Union[str, Any] = df.rename(str.capitalize ,axis='columns' ) # make the cols as narrow as possible __lowerCamelCase : List[str] = df.rename(lambda _lowerCAmelCase : c.replace('_' ,'<br>' ) ,axis='columns' ) __lowerCamelCase : Union[str, Any] = df.rename(lambda _lowerCAmelCase : c.replace('_' ,'\n' ) ,axis='columns' ) __lowerCamelCase : Tuple = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_lowerCAmelCase ,floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_lowerCAmelCase ,floatfmt='.2f' )] print('\n\n'.join(_lowerCAmelCase ) ) def a_ ( ) -> List[Any]: __lowerCamelCase : int = argparse.ArgumentParser() parser.add_argument( '--base-cmd' ,default=_lowerCAmelCase ,type=_lowerCAmelCase ,required=_lowerCAmelCase ,help='Base cmd' ,) parser.add_argument( '--variations' ,default=_lowerCAmelCase ,type=_lowerCAmelCase ,nargs='+' ,required=_lowerCAmelCase ,help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' ,) parser.add_argument( '--base-variation' ,default=_lowerCAmelCase ,type=_lowerCAmelCase ,help='Baseline variation to compare to. if None the minimal target value will be used to compare against' ,) parser.add_argument( '--target-metric-key' ,default=_lowerCAmelCase ,type=_lowerCAmelCase ,required=_lowerCAmelCase ,help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' ,) parser.add_argument( '--report-metric-keys' ,default='' ,type=_lowerCAmelCase ,help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' ,) parser.add_argument( '--repeat-times' ,default=1 ,type=_lowerCAmelCase ,help='How many times to re-run each variation - an average will be reported' ,) parser.add_argument( '--output_dir' ,default='output_benchmark' ,type=_lowerCAmelCase ,help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' ,) parser.add_argument( '--verbose' ,default=_lowerCAmelCase ,action='store_true' ,help='Whether to show the outputs of each run or just the benchmark progress' ,) __lowerCamelCase : Any = parser.parse_args() __lowerCamelCase : List[str] = args.output_dir Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) __lowerCamelCase : Dict = get_base_command(_lowerCAmelCase ,_lowerCAmelCase ) # split each dimension into its --foo variations __lowerCamelCase : Optional[Any] = [list(map(str.strip ,re.split(r'\|' ,_lowerCAmelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty __lowerCamelCase : List[str] = list(map(str.strip ,map(' '.join ,itertools.product(*_lowerCAmelCase ) ) ) ) __lowerCamelCase : int = max(len(_lowerCAmelCase ) for x in variations ) # split wanted keys __lowerCamelCase : Union[str, Any] = args.report_metric_keys.split() # capture prints into a log file for convenience __lowerCamelCase : str = F'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(F'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(F'and this script\'s output is also piped into {report_fn}' ) __lowerCamelCase : Optional[int] = Tee(_lowerCAmelCase ) print(F'\n*** Running {len(_lowerCAmelCase )} benchmarks:' ) print(F'Base command: {" ".join(_lowerCAmelCase )}' ) __lowerCamelCase : int = 'variation' __lowerCamelCase : Optional[Any] = [] for id, variation in enumerate(tqdm(_lowerCAmelCase ,desc='Total completion: ' ,leave=_lowerCAmelCase ) ): __lowerCamelCase : int = base_cmd + variation.split() results.append( process_run( id + 1 ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,args.target_metric_key ,_lowerCAmelCase ,args.repeat_times ,_lowerCAmelCase ,args.verbose ,) ) process_results(_lowerCAmelCase ,args.target_metric_key ,_lowerCAmelCase ,args.base_variation ,_lowerCAmelCase ) if __name__ == "__main__": main()
208
'''simple docstring''' def a_ ( _lowerCAmelCase ) -> list: if n_term == "": return [] __lowerCamelCase : list = [] for temp in range(int(_lowerCAmelCase ) ): series.append(F'1/{temp + 1}' if series else '1' ) return series if __name__ == "__main__": _UpperCamelCase = input('Enter the last number (nth term) of the Harmonic Series') print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n') print(harmonic_series(nth_term))
208
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig _snake_case = { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/config.json", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/config.json", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/config.json", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/config.json", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/config.json", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/config.json", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json", } class UpperCAmelCase_ ( __lowercase): lowerCamelCase__ = 'albert' def __init__( self, __a=3_0000, __a=128, __a=4096, __a=12, __a=1, __a=64, __a=1_6384, __a=1, __a="gelu_new", __a=0, __a=0, __a=512, __a=2, __a=0.02, __a=1E-12, __a=0.1, __a="absolute", __a=0, __a=2, __a=3, **__a, ): '''simple docstring''' super().__init__(pad_token_id=_a, bos_token_id=_a, eos_token_id=_a, **_a) _lowerCAmelCase : str = vocab_size _lowerCAmelCase : Any = embedding_size _lowerCAmelCase : Any = hidden_size _lowerCAmelCase : Any = num_hidden_layers _lowerCAmelCase : Dict = num_hidden_groups _lowerCAmelCase : Any = num_attention_heads _lowerCAmelCase : List[str] = inner_group_num _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : List[str] = intermediate_size _lowerCAmelCase : Dict = hidden_dropout_prob _lowerCAmelCase : str = attention_probs_dropout_prob _lowerCAmelCase : Optional[int] = max_position_embeddings _lowerCAmelCase : List[Any] = type_vocab_size _lowerCAmelCase : List[Any] = initializer_range _lowerCAmelCase : Optional[Any] = layer_norm_eps _lowerCAmelCase : str = classifier_dropout_prob _lowerCAmelCase : Any = position_embedding_type class UpperCAmelCase_ ( __lowercase): @property def snake_case__ ( self): '''simple docstring''' if self.task == "multiple-choice": _lowerCAmelCase : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: _lowerCAmelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ])
350
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor _snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( a): def __init__( self, *__a, **__a): '''simple docstring''' warnings.warn( "The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use VideoMAEImageProcessor instead.", __a, ) super().__init__(*__a, **__a)
300
0
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) __snake_case = _symbol_database.Default() __snake_case = _descriptor_pool.Default().AddSerializedFile( b"""\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03""" ) __snake_case = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, """sentencepiece_model_pb2""", _globals) if _descriptor._USE_C_DESCRIPTORS is False: __snake_case = None __snake_case = b"""H\003""" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" __snake_case = 45 __snake_case = 15_81 __snake_case = 15_17 __snake_case = 15_70 __snake_case = 15_84 __snake_case = 17_93 __snake_case = 17_95 __snake_case = 19_16 __snake_case = 18_64 __snake_case = 19_05 __snake_case = 19_19 __snake_case = 24_29 __snake_case = 22_08 __snake_case = 24_18 __snake_case = 23_23 __snake_case = 24_07 # @@protoc_insertion_point(module_scope)
176
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--original_config_file""", type=str, required=True, help="""The YAML config file corresponding to the original architecture.""", ) parser.add_argument( """--num_in_channels""", default=None, type=int, help="""The number of input channels. If `None` number of input channels will be automatically inferred.""", ) parser.add_argument( """--image_size""", default=5_12, type=int, help=( """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2""" """ Base. Use 768 for Stable Diffusion v2.""" ), ) parser.add_argument( """--extract_ema""", action="""store_true""", help=( """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights""" """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield""" """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.""" ), ) parser.add_argument( """--upcast_attention""", action="""store_true""", help=( """Whether the attention computation should always be upcasted. This is necessary when running stable""" """ diffusion 2.1.""" ), ) parser.add_argument( """--from_safetensors""", action="""store_true""", help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""", ) parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") def _lowercase ( UpperCamelCase_ ) -> Dict: '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(F'could not parse string as bool {string}' ) parser.add_argument( """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool ) parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int) __snake_case = parser.parse_args() __snake_case = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
176
1
"""simple docstring""" from __future__ import annotations __A = 'Muhammad Umer Farooq' __A = 'MIT' __A = '1.0.0' __A = 'Muhammad Umer Farooq' __A = 'contact@muhammadumerfarooq.me' __A = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class lowerCamelCase__ ( __magic_name__ ): '''simple docstring''' def __init__( self , __UpperCAmelCase ) -> None: super().__init__() _lowerCAmelCase =[] _lowerCAmelCase =domain def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _lowerCAmelCase =parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _lowerCamelCase(__UpperCamelCase ) -> str: return ".".join(get_sub_domain_name(__UpperCamelCase ).split(""".""" )[-2:] ) def _lowerCamelCase(__UpperCamelCase ) -> str: return parse.urlparse(__UpperCamelCase ).netloc def _lowerCamelCase(__UpperCamelCase = "https://github.com" ) -> list[str]: _lowerCAmelCase =get_domain_name(__UpperCamelCase ) # Initialize the parser _lowerCAmelCase =Parser(__UpperCamelCase ) try: # Open URL _lowerCAmelCase =requests.get(__UpperCamelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _lowerCAmelCase =set() for link in parser.urls: # open URL. # read = requests.get(link) try: _lowerCAmelCase =requests.get(__UpperCamelCase ) # Get the valid email. _lowerCAmelCase =re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__UpperCamelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__UpperCamelCase ) if __name__ == "__main__": __A = emails_from_url('https://github.com') print(F"""{len(emails)} emails found:""") print('\n'.join(sorted(emails)))
341
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available __A = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys __A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
341
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE( metaclass=A ): SCREAMING_SNAKE_CASE_ : Tuple = ['''onnx'''] def __init__( self ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" requires_backends(self ,['''onnx'''] ) @classmethod def _UpperCamelCase ( cls ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" requires_backends(cls ,['''onnx'''] ) @classmethod def _UpperCamelCase ( cls ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" requires_backends(cls ,['''onnx'''] )
191
"""simple docstring""" def __lowerCamelCase ( a_ : list ) -> list: if len(a_ ) < 2: return collection def circle_sort_util(a_ : list , a_ : int , a_ : int ) -> bool: __SCREAMING_SNAKE_CASE :int = False if low == high: return swapped __SCREAMING_SNAKE_CASE :int = low __SCREAMING_SNAKE_CASE :Tuple = high while left < right: if collection[left] > collection[right]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :str = ( collection[right], collection[left], ) __SCREAMING_SNAKE_CASE :Optional[int] = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Tuple = ( collection[right + 1], collection[left], ) __SCREAMING_SNAKE_CASE :Tuple = True __SCREAMING_SNAKE_CASE :int = low + int((high - low) / 2 ) __SCREAMING_SNAKE_CASE :int = circle_sort_util(a_ , a_ , a_ ) __SCREAMING_SNAKE_CASE :Union[str, Any] = circle_sort_util(a_ , mid + 1 , a_ ) return swapped or left_swap or right_swap __SCREAMING_SNAKE_CASE :Optional[Any] = True while is_not_sorted is True: __SCREAMING_SNAKE_CASE :Tuple = circle_sort_util(a_ , 0 , len(a_ ) - 1 ) return collection if __name__ == "__main__": lowerCamelCase_ = input("Enter numbers separated by a comma:\n").strip() lowerCamelCase_ = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
191
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A ={ 'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ 'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegaForCausalLM', 'MegaForMaskedLM', 'MegaForMultipleChoice', 'MegaForQuestionAnswering', 'MegaForSequenceClassification', 'MegaForTokenClassification', 'MegaModel', 'MegaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys __A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
362
'''simple docstring''' import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __A ='\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' __A ='\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n' __A ='\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=["About 95 species are currently accepted ."]\n >>> predictions=["About 95 you now get in ."]\n >>> references=[["About 95 species are currently known ."]]\n >>> wiki_split = datasets.load_metric("wiki_split")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n' def _UpperCamelCase ( UpperCamelCase__ ): def remove_articles(UpperCamelCase__ ): UpperCAmelCase__ : Tuple = re.compile(R"""\b(a|an|the)\b""" , re.UNICODE ) return re.sub(UpperCamelCase__ , """ """ , UpperCamelCase__ ) def white_space_fix(UpperCamelCase__ ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__ ): UpperCAmelCase__ : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase__ ) ) ) ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): return int(normalize_answer(UpperCamelCase__ ) == normalize_answer(UpperCamelCase__ ) ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Any = [any(compute_exact(UpperCamelCase__ , UpperCamelCase__ ) for ref in refs ) for pred, refs in zip(UpperCamelCase__ , UpperCamelCase__ )] return (sum(UpperCamelCase__ ) / len(UpperCamelCase__ )) * 1_0_0 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : List[Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCAmelCase__ : List[Any] = Counter(UpperCamelCase__ ) UpperCAmelCase__ : str = Counter(UpperCamelCase__ ) UpperCAmelCase__ : Dict = Counter() for sgram, scount in sgramcounter.items(): UpperCAmelCase__ : Dict = scount * numref UpperCAmelCase__ : int = Counter(UpperCamelCase__ ) UpperCAmelCase__ : Optional[int] = Counter() for cgram, ccount in cgramcounter.items(): UpperCAmelCase__ : Union[str, Any] = ccount * numref # KEEP UpperCAmelCase__ : str = sgramcounter_rep & cgramcounter_rep UpperCAmelCase__ : List[Any] = keepgramcounter_rep & rgramcounter UpperCAmelCase__ : Dict = sgramcounter_rep & rgramcounter UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Union[str, Any] = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCAmelCase__ : List[str] = 1 UpperCAmelCase__ : Optional[Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[int] = keeptmpscorea / len(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCAmelCase__ : Any = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCAmelCase__ : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCAmelCase__ : str = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCAmelCase__ : str = sgramcounter_rep - cgramcounter_rep UpperCAmelCase__ : Optional[Any] = delgramcounter_rep - rgramcounter UpperCAmelCase__ : List[str] = sgramcounter_rep - rgramcounter UpperCAmelCase__ : str = 0 UpperCAmelCase__ : List[Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCAmelCase__ : Union[str, Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[Any] = deltmpscorea / len(UpperCamelCase__ ) # ADDITION UpperCAmelCase__ : Tuple = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) UpperCAmelCase__ : Optional[Any] = set(UpperCamelCase__ ) & set(UpperCamelCase__ ) UpperCAmelCase__ : List[str] = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) UpperCAmelCase__ : str = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : List[Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[int] = addtmpscore / len(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : int = addtmpscore / len(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCAmelCase__ : int = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Dict = len(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = ssent.split(""" """ ) UpperCAmelCase__ : Optional[int] = csent.split(""" """ ) UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Tuple = [] UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Tuple = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : List[Any] = [] for rsent in rsents: UpperCAmelCase__ : List[str] = rsent.split(""" """ ) UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : str = [] UpperCAmelCase__ : Dict = [] ragramslist.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Optional[int] = ragrams[i] + """ """ + ragrams[i + 1] ragrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : Union[str, Any] = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] ragrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : Any = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3] ragrams.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Optional[int] = sagrams[i] + """ """ + sagrams[i + 1] sagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : Dict = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] sagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : str = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3] sagrams.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Dict = cagrams[i] + """ """ + cagrams[i + 1] cagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : int = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] cagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : List[Any] = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3] cagrams.append(UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Optional[Any] = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : str = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Any = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Optional[int] = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCAmelCase__ : Union[str, Any] = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCAmelCase__ : Dict = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCAmelCase__ : List[Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ = True , UpperCamelCase__ = "13a" , UpperCamelCase__ = True ): # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCAmelCase__ : List[str] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCAmelCase__ : Tuple = sacrebleu.metrics.bleu._get_tokenizer(UpperCamelCase__ )()(UpperCamelCase__ ) else: UpperCAmelCase__ : Tuple = sacrebleu.TOKENIZERS[tokenizer]()(UpperCamelCase__ ) elif tokenizer == "moses": UpperCAmelCase__ : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(UpperCamelCase__ , return_str=UpperCamelCase__ , escape=UpperCamelCase__ ) elif tokenizer == "penn": UpperCAmelCase__ : Dict = sacremoses.MosesTokenizer().penn_tokenize(UpperCamelCase__ , return_str=UpperCamelCase__ ) else: UpperCAmelCase__ : List[Any] = sentence if not return_str: UpperCAmelCase__ : List[str] = normalized_sent.split() return normalized_sent def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): if not (len(UpperCamelCase__ ) == len(UpperCamelCase__ ) == len(UpperCamelCase__ )): raise ValueError("""Sources length must match predictions and references lengths.""" ) UpperCAmelCase__ : Optional[int] = 0 for src, pred, refs in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): sari_score += SARIsent(normalize(UpperCamelCase__ ) , normalize(UpperCamelCase__ ) , [normalize(UpperCamelCase__ ) for sent in refs] ) UpperCAmelCase__ : Optional[int] = sari_score / len(UpperCamelCase__ ) return 1_0_0 * sari_score def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__="exp" , UpperCamelCase__=None , UpperCamelCase__=False , UpperCamelCase__=False , UpperCamelCase__=False , ): UpperCAmelCase__ : int = len(references[0] ) if any(len(UpperCamelCase__ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) UpperCAmelCase__ : int = [[refs[i] for refs in references] for i in range(UpperCamelCase__ )] UpperCAmelCase__ : int = sacrebleu.corpus_bleu( UpperCamelCase__ , UpperCamelCase__ , smooth_method=UpperCamelCase__ , smooth_value=UpperCamelCase__ , force=UpperCamelCase__ , lowercase=UpperCamelCase__ , use_effective_order=UpperCamelCase__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def snake_case__ ( self): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence"""), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""") , id="""references"""), }) , codebase_urls=[ """https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""", """https://github.com/cocoxu/simplification/blob/master/SARI.py""", """https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""", """https://github.com/mjpost/sacreBLEU""", ] , reference_urls=[ """https://www.aclweb.org/anthology/Q16-1029.pdf""", """https://github.com/mjpost/sacreBLEU""", """https://en.wikipedia.org/wiki/BLEU""", """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""", ] , ) def snake_case__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = {} result.update({"""sari""": compute_sari(sources=_lowerCamelCase , predictions=_lowerCamelCase , references=_lowerCamelCase)}) result.update({"""sacrebleu""": compute_sacrebleu(predictions=_lowerCamelCase , references=_lowerCamelCase)}) result.update({"""exact""": compute_em(predictions=_lowerCamelCase , references=_lowerCamelCase)}) return result
283
0
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel A__ : Dict =HfApi() A__ : Tuple ={} # fmt: off A__ : Union[str, Any] =torch.tensor([ -0.7_515, -1.6_883, 0.2_420, 0.0_300, 0.6_347, 1.3_433, -1.1_743, -3.7_467, 1.2_342, -2.2_485, 0.4_636, 0.8_076, -0.7_991, 0.3_969, 0.8_498, 0.9_189, -1.8_887, -3.3_522, 0.7_639, 0.2_040, 0.6_271, -2.7_148, -1.6_316, 3.0_839, 0.3_186, 0.2_721, -0.9_759, -1.2_461, 2.6_257, 1.3_557 ]) A__ : List[str] =torch.tensor([ -2.3_639, -2.5_344, 0.0_054, -0.6_674, 1.5_990, 1.0_158, 0.3_124, -2.1_436, 1.8_795, -2.5_429, -0.1_566, -0.3_973, 1.2_490, 2.6_447, 1.2_283, -0.5_208, -2.8_154, -3.5_119, 2.3_838, 1.2_033, 1.7_201, -2.1_256, -1.4_576, 2.7_948, 2.4_204, -0.9_752, -1.2_546, 0.8_027, 3.2_758, 3.1_365 ]) A__ : Tuple =torch.tensor([ -0.6_531, -0.6_891, -0.3_172, -0.5_375, -0.9_140, -0.5_367, -0.1_175, -0.7_869, -0.3_808, -0.4_513, -0.2_098, -0.0_083, 0.3_183, 0.5_140, 0.2_247, -0.1_304, -0.1_302, -0.2_802, -0.2_084, -0.2_025, -0.4_967, -0.4_873, -0.0_861, 0.6_925, 0.0_250, 0.1_290, -0.1_543, 0.6_316, 1.0_460, 1.4_943 ]) A__ : Union[str, Any] =torch.tensor([ 0.0_911, 0.1_107, 0.0_182, 0.0_435, -0.0_805, -0.0_608, 0.0_381, 0.2_172, -0.0_280, 0.1_327, -0.0_299, -0.0_255, -0.0_050, -0.1_170, -0.1_046, 0.0_309, 0.1_367, 0.1_728, -0.0_533, -0.0_748, -0.0_534, 0.1_624, 0.0_384, -0.1_805, -0.0_707, 0.0_642, 0.0_220, -0.0_134, -0.1_333, -0.1_505 ]) A__ : Union[str, Any] =torch.tensor([ 0.1_321, 0.1_337, 0.0_440, 0.0_622, -0.0_591, -0.0_370, 0.0_503, 0.2_133, -0.0_177, 0.1_415, -0.0_116, -0.0_112, 0.0_044, -0.0_980, -0.0_789, 0.0_395, 0.1_502, 0.1_785, -0.0_488, -0.0_514, -0.0_404, 0.1_539, 0.0_454, -0.1_559, -0.0_665, 0.0_659, 0.0_383, -0.0_005, -0.1_266, -0.1_386 ]) A__ : Union[str, Any] =torch.tensor([ 0.1_154, 0.1_218, 0.0_307, 0.0_526, -0.0_711, -0.0_541, 0.0_366, 0.2_078, -0.0_267, 0.1_317, -0.0_226, -0.0_193, -0.0_014, -0.1_055, -0.0_902, 0.0_330, 0.1_391, 0.1_709, -0.0_562, -0.0_693, -0.0_560, 0.1_482, 0.0_381, -0.1_683, -0.0_681, 0.0_661, 0.0_331, -0.0_046, -0.1_268, -0.1_431 ]) A__ : Optional[int] =torch.tensor([ 0.1_192, 0.1_240, 0.0_414, 0.0_606, -0.0_557, -0.0_412, 0.0_430, 0.2_042, -0.0_200, 0.1_385, -0.0_115, -0.0_132, 0.0_017, -0.0_965, -0.0_802, 0.0_398, 0.1_433, 0.1_747, -0.0_458, -0.0_533, -0.0_407, 0.1_545, 0.0_419, -0.1_574, -0.0_645, 0.0_626, 0.0_341, -0.0_010, -0.1_199, -0.1_390 ]) A__ : Tuple =torch.tensor([ 0.1_075, 0.1_074, 0.0_205, 0.0_431, -0.0_774, -0.0_607, 0.0_298, 0.2_042, -0.0_320, 0.1_267, -0.0_281, -0.0_250, -0.0_064, -0.1_091, -0.0_946, 0.0_290, 0.1_328, 0.1_650, -0.0_580, -0.0_738, -0.0_586, 0.1_440, 0.0_337, -0.1_746, -0.0_712, 0.0_605, 0.0_250, -0.0_099, -0.1_316, -0.1_473 ]) A__ : List[Any] =torch.tensor([ -1.4_572, -2.0_481, -0.0_414, -0.6_005, 1.4_136, 0.5_848, 0.4_028, -2.7_330, 1.2_212, -2.1_228, 0.2_155, 0.4_039, 0.7_662, 2.0_535, 0.7_477, -0.3_243, -2.1_758, -2.7_648, 1.6_947, 0.7_026, 1.2_338, -1.6_078, -0.8_682, 2.2_810, 1.8_574, -0.5_718, -0.5_586, -0.0_186, 2.3_415, 2.1_251]) A__ : Tuple =torch.tensor([ -1.3_690, -1.9_720, -0.4_090, -0.6_966, 1.4_660, 0.9_938, -0.1_385, -2.7_324, 0.7_736, -1.8_917, 0.2_923, 0.4_293, 0.1_693, 1.4_112, 1.1_887, -0.3_181, -2.2_160, -2.6_381, 1.3_170, 0.8_163, 0.9_240, -1.6_544, -0.6_099, 2.5_259, 1.6_430, -0.9_090, -0.9_392, -0.0_126, 2.4_268, 2.3_266 ]) A__ : List[str] =torch.tensor([ -1.3_525, -1.9_628, -0.3_956, -0.6_860, 1.4_664, 1.0_014, -0.1_259, -2.7_212, 0.7_772, -1.8_811, 0.2_996, 0.4_388, 0.1_704, 1.4_029, 1.1_701, -0.3_027, -2.2_053, -2.6_287, 1.3_350, 0.8_131, 0.9_274, -1.6_292, -0.6_098, 2.5_131, 1.6_505, -0.8_958, -0.9_298, -0.0_151, 2.4_257, 2.3_355 ]) A__ : int =torch.tensor([ -2.0_585, -2.7_897, -0.2_850, -0.8_940, 1.9_052, 0.5_702, 0.6_345, -3.8_959, 1.5_932, -3.2_319, 0.1_974, 0.0_287, 1.7_566, 2.6_543, 0.8_387, -0.5_351, -3.2_736, -4.3_375, 2.9_029, 1.6_390, 1.4_640, -2.1_701, -1.9_013, 2.9_341, 3.4_981, -0.6_255, -1.1_644, -0.1_591, 3.7_097, 3.2_066 ]) A__ : Union[str, Any] =torch.tensor([ -2.3_139, -2.5_594, -0.0_197, -0.6_785, 1.7_001, 1.1_606, 0.3_075, -2.1_740, 1.8_071, -2.5_630, -0.0_926, -0.3_811, 1.2_116, 2.6_246, 1.2_731, -0.5_398, -2.8_153, -3.6_140, 2.3_893, 1.3_262, 1.6_258, -2.1_856, -1.3_267, 2.8_395, 2.3_779, -1.0_623, -1.2_468, 0.8_959, 3.3_367, 3.2_243 ]) A__ : Dict =torch.tensor([ -2.0_628, -2.7_667, -0.2_089, -0.8_263, 2.0_539, 0.5_992, 0.6_495, -3.8_336, 1.6_025, -3.2_817, 0.1_721, -0.0_633, 1.7_516, 2.7_039, 0.8_100, -0.5_908, -3.2_113, -4.4_343, 2.9_257, 1.3_632, 1.5_562, -2.1_489, -1.9_894, 3.0_560, 3.3_396, -0.7_328, -1.0_417, 0.0_383, 3.7_093, 3.2_343 ]) A__ : Optional[int] =torch.tensor([ -1.4_574, -2.0_569, -0.0_473, -0.6_117, 1.4_018, 0.5_769, 0.4_129, -2.7_344, 1.2_241, -2.1_397, 0.2_000, 0.3_937, 0.7_616, 2.0_453, 0.7_324, -0.3_391, -2.1_746, -2.7_744, 1.6_963, 0.6_921, 1.2_187, -1.6_172, -0.8_877, 2.2_439, 1.8_471, -0.5_839, -0.5_605, -0.0_464, 2.3_250, 2.1_219 ]) # fmt: on A__ : Union[str, Any] =api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": A__ : Optional[Any] ="""/home/patrick/google_checkpoints/""" + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): A__ : str =UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: A__ : int =UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) A__ : Optional[Any] =torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) A__ : str =torch.tensor([10] * noise.shape[0]) with torch.no_grad(): A__ : List[Any] =model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1e-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
70
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : Union[str, Any] = { """configuration_funnel""": ["""FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FunnelConfig"""], """convert_funnel_original_tf_checkpoint_to_pytorch""": [], """tokenization_funnel""": ["""FunnelTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ["""FunnelTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ """FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """FunnelBaseModel""", """FunnelForMaskedLM""", """FunnelForMultipleChoice""", """FunnelForPreTraining""", """FunnelForQuestionAnswering""", """FunnelForSequenceClassification""", """FunnelForTokenClassification""", """FunnelModel""", """FunnelPreTrainedModel""", """load_tf_weights_in_funnel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = [ """TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFFunnelBaseModel""", """TFFunnelForMaskedLM""", """TFFunnelForMultipleChoice""", """TFFunnelForPreTraining""", """TFFunnelForQuestionAnswering""", """TFFunnelForSequenceClassification""", """TFFunnelForTokenClassification""", """TFFunnelModel""", """TFFunnelPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
75
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : int = logging.get_logger(__name__) lowercase__ : List[str] = { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json''' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : Tuple = """speech_to_text_2""" _lowerCAmelCase : Dict = ["""past_key_values"""] _lowerCAmelCase : List[str] = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : List[str] , lowercase_ : Any=10000 , lowercase_ : List[Any]=6 , lowercase_ : Optional[int]=2048 , lowercase_ : Tuple=4 , lowercase_ : int=0.0 , lowercase_ : Optional[Any]=True , lowercase_ : Any="relu" , lowercase_ : Optional[int]=256 , lowercase_ : Dict=0.1 , lowercase_ : Optional[Any]=0.0 , lowercase_ : Any=0.0 , lowercase_ : Optional[Any]=0.02 , lowercase_ : Dict=2 , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=1 , lowercase_ : Tuple=0 , lowercase_ : int=2 , lowercase_ : str=1024 , **lowercase_ : List[str] , ): snake_case_ : List[Any] = vocab_size snake_case_ : str = d_model snake_case_ : List[Any] = decoder_ffn_dim snake_case_ : Dict = decoder_layers snake_case_ : str = decoder_attention_heads snake_case_ : int = dropout snake_case_ : Optional[int] = attention_dropout snake_case_ : Dict = activation_dropout snake_case_ : Any = activation_function snake_case_ : str = init_std snake_case_ : List[str] = decoder_layerdrop snake_case_ : List[Any] = use_cache snake_case_ : Union[str, Any] = decoder_layers snake_case_ : Optional[Any] = scale_embedding # scale factor will be sqrt(d_model) if True snake_case_ : List[str] = max_target_positions super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , decoder_start_token_id=lowercase_ , **lowercase_ , )
155
"""simple docstring""" def __lowercase ( _a = 4_000_000 ): snake_case_ : Dict = [] snake_case_, snake_case_ : List[str] = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(_a ) snake_case_, snake_case_ : str = b, a + b return sum(_a ) if __name__ == "__main__": print(f'{solution() = }')
155
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int lowerCAmelCase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _a ( datasets.BuilderConfig ): _lowercase : Optional[datasets.Features] = None def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): """simple docstring""" import pyspark def generate_fn(): lowercase__ = df.select('''*''' , pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: lowercase__ = df_with_partition_id.select('''*''' ).where(f'part_id = {partition_id}' ).drop('''part_id''' ) lowercase__ = partition_df.collect() lowercase__ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _a ( _BaseExamplesIterable ): def __init__( self: List[str] , UpperCamelCase_: "pyspark.sql.DataFrame" , UpperCamelCase_: Tuple=None , ) -> int: """simple docstring""" lowercase__ = df lowercase__ = partition_order or range(self.df.rdd.getNumPartitions() ) lowercase__ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self: Optional[Any] ) -> List[str]: """simple docstring""" yield from self.generate_examples_fn() def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: np.random.Generator ) -> "SparkExamplesIterable": """simple docstring""" lowercase__ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(UpperCamelCase_ ) return SparkExamplesIterable(self.df , partition_order=UpperCamelCase_ ) def lowerCamelCase_ ( self: str , UpperCamelCase_: int , UpperCamelCase_: int ) -> "SparkExamplesIterable": """simple docstring""" lowercase__ = self.split_shard_indices_by_worker(UpperCamelCase_ , UpperCamelCase_ ) return SparkExamplesIterable(self.df , partition_order=UpperCamelCase_ ) @property def lowerCamelCase_ ( self: int ) -> int: """simple docstring""" return len(self.partition_order ) class _a ( datasets.DatasetBuilder ): _lowercase : Tuple = SparkConfig def __init__( self: Any , UpperCamelCase_: "pyspark.sql.DataFrame" , UpperCamelCase_: str = None , UpperCamelCase_: str = None , **UpperCamelCase_: Tuple , ) -> int: """simple docstring""" import pyspark lowercase__ = pyspark.sql.SparkSession.builder.getOrCreate() lowercase__ = df lowercase__ = working_dir super().__init__( cache_dir=UpperCamelCase_ , config_name=str(self.df.semanticHash() ) , **UpperCamelCase_ , ) def lowerCamelCase_ ( self: int ) -> List[Any]: """simple docstring""" def create_cache_and_write_probe(UpperCamelCase_: Dict ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=UpperCamelCase_ ) lowercase__ = os.path.join(self._cache_dir , '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(UpperCamelCase_ , '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''' , '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowercase__ = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(UpperCamelCase_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def lowerCamelCase_ ( self: str ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase_ ( self: Tuple , UpperCamelCase_: datasets.download.download_manager.DownloadManager ) -> Optional[int]: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: List[str] ) -> List[Any]: """simple docstring""" import pyspark def get_arrow_batch_size(UpperCamelCase_: Optional[Any] ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) lowercase__ = self.df.count() lowercase__ = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowercase__ = ( self.df.limit(UpperCamelCase_ ) .repartition(1 ) .mapInArrow(UpperCamelCase_ , '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowercase__ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowercase__ = min(UpperCamelCase_ , int(approx_total_size / max_shard_size ) ) lowercase__ = self.df.repartition(UpperCamelCase_ ) def lowerCamelCase_ ( self: Dict , UpperCamelCase_: str , UpperCamelCase_: str , UpperCamelCase_: int , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: """simple docstring""" import pyspark lowercase__ = ParquetWriter if file_format == '''parquet''' else ArrowWriter lowercase__ = os.path.join(self._working_dir , os.path.basename(UpperCamelCase_ ) ) if self._working_dir else fpath lowercase__ = file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowercase__ = self.config.features lowercase__ = self._writer_batch_size lowercase__ = self._fs.storage_options def write_arrow(UpperCamelCase_: Tuple ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowercase__ = pyspark.TaskContext().taskAttemptId() lowercase__ = next(UpperCamelCase_ , UpperCamelCase_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) lowercase__ = 0 lowercase__ = writer_class( features=UpperCamelCase_ , path=working_fpath.replace('''SSSSS''' , f'{shard_id:05d}' ).replace('''TTTTT''' , f'{task_id:05d}' ) , writer_batch_size=UpperCamelCase_ , storage_options=UpperCamelCase_ , embed_local_files=UpperCamelCase_ , ) lowercase__ = pa.Table.from_batches([first_batch] ) writer.write_table(UpperCamelCase_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowercase__ , lowercase__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) shard_id += 1 lowercase__ = writer_class( features=writer._features , path=working_fpath.replace('''SSSSS''' , f'{shard_id:05d}' ).replace('''TTTTT''' , f'{task_id:05d}' ) , writer_batch_size=UpperCamelCase_ , storage_options=UpperCamelCase_ , embed_local_files=UpperCamelCase_ , ) lowercase__ = pa.Table.from_batches([batch] ) writer.write_table(UpperCamelCase_ ) if writer._num_bytes > 0: lowercase__ , lowercase__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(UpperCamelCase_ ) ): lowercase__ = os.path.join(os.path.dirname(UpperCamelCase_ ) , os.path.basename(UpperCamelCase_ ) ) shutil.move(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = ( self.df.mapInArrow(UpperCamelCase_ , '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ) , pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ) , pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ) , pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def lowerCamelCase_ ( self: Any , UpperCamelCase_: "datasets.SplitGenerator" , UpperCamelCase_: str = "arrow" , UpperCamelCase_: Optional[Union[str, int]] = None , UpperCamelCase_: Optional[int] = None , **UpperCamelCase_: Optional[int] , ) -> str: """simple docstring""" self._validate_cache_dir() lowercase__ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(UpperCamelCase_ ) lowercase__ = not is_remote_filesystem(self._fs ) lowercase__ = os.path.join if is_local else posixpath.join lowercase__ = '''-TTTTT-SSSSS-of-NNNNN''' lowercase__ = f'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' lowercase__ = path_join(self._output_dir , UpperCamelCase_ ) lowercase__ = 0 lowercase__ = 0 lowercase__ = 0 lowercase__ = [] lowercase__ = [] for task_id, content in self._prepare_split_single(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): ( ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(UpperCamelCase_ ) lowercase__ = total_num_examples lowercase__ = total_num_bytes # should rename everything at the end logger.debug(f'Renaming {total_shards} shards.' ) if total_shards > 1: lowercase__ = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowercase__ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( UpperCamelCase_: int , UpperCamelCase_: int , UpperCamelCase_: int , ): rename( UpperCamelCase_ , fpath.replace('''SSSSS''' , f'{shard_id:05d}' ).replace('''TTTTT''' , f'{task_id:05d}' ) , fpath.replace('''TTTTT-SSSSS''' , f'{global_shard_id:05d}' ).replace('''NNNNN''' , f'{total_shards:05d}' ) , ) lowercase__ = [] lowercase__ = 0 for i in range(len(UpperCamelCase_ ) ): lowercase__ , lowercase__ = task_id_and_num_shards[i] for shard_id in range(UpperCamelCase_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(UpperCamelCase_ , len(UpperCamelCase_ ) ).map(lambda UpperCamelCase_ : _rename_shard(*UpperCamelCase_ ) ).collect() else: # don't use any pattern lowercase__ = 0 lowercase__ = task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''' , f'{shard_id:05d}' ).replace('''TTTTT''' , f'{task_id:05d}' ) , fpath.replace(UpperCamelCase_ , '''''' ) , ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: "datasets.SplitGenerator" , ) -> SparkExamplesIterable: """simple docstring""" return SparkExamplesIterable(self.df )
110
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class lowerCamelCase__ ( lowerCAmelCase , lowerCAmelCase): SCREAMING_SNAKE_CASE__ = 1 @register_to_config def __init__(self , UpperCAmelCase=2_0_0_0 , UpperCAmelCase=0.1 , UpperCAmelCase=2_0 , UpperCAmelCase=1e-3 ) -> List[str]: _lowercase =None _lowercase =None _lowercase =None def __A (self , UpperCAmelCase , UpperCAmelCase = None ) -> str: _lowercase =torch.linspace(1 , self.config.sampling_eps , UpperCAmelCase , device=UpperCAmelCase ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None ) -> Optional[int]: if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score _lowercase =( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) _lowercase =torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) _lowercase =std.flatten() while len(std.shape ) < len(score.shape ): _lowercase =std.unsqueeze(-1 ) _lowercase =-score / std # compute _lowercase =-1.0 / len(self.timesteps ) _lowercase =self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) _lowercase =beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): _lowercase =beta_t.unsqueeze(-1 ) _lowercase =-0.5 * beta_t * x _lowercase =torch.sqrt(UpperCAmelCase ) _lowercase =drift - diffusion**2 * score _lowercase =x + drift * dt # add noise _lowercase =randn_tensor(x.shape , layout=x.layout , generator=UpperCAmelCase , device=x.device , dtype=x.dtype ) _lowercase =x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__(self ) -> str: return self.config.num_train_timesteps
5
0
def lowerCAmelCase_ ( __A ) -> list: '''simple docstring''' UpperCAmelCase__ = len(__A ) for _ in range(__A ): for i in range(_ % 2, arr_size - 1, 2 ): if arr[i + 1] < arr[i]: UpperCAmelCase__ , UpperCAmelCase__ = arr[i + 1], arr[i] return arr if __name__ == "__main__": UpperCamelCase__ = list(range(1_0, 0, -1)) print(f'''Original: {arr}. Sorted: {odd_even_transposition(arr)}''')
355
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCamelCase__ = 1_6 UpperCamelCase__ = 3_2 def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' return int(x / 2**20 ) class A : def __enter__(self : Dict ) -> int: """simple docstring""" gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero UpperCAmelCase__ = torch.cuda.memory_allocated() return self def __exit__(self : List[str] , *__UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" gc.collect() torch.cuda.empty_cache() UpperCAmelCase__ = torch.cuda.memory_allocated() UpperCAmelCase__ = torch.cuda.max_memory_allocated() UpperCAmelCase__ = bamb(self.end - self.begin ) UpperCAmelCase__ = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCAmelCase_ ( __A, __A = 16, __A = "bert-base-cased", __A = 320, __A = 160, ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCAmelCase__ = load_dataset( "glue", "mrpc", split={"train": f"""train[:{n_train}]""", "validation": f"""validation[:{n_val}]"""} ) def tokenize_function(__A ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase__ = tokenizer(examples["sentence1"], examples["sentence2"], truncation=__A, max_length=__A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase__ = datasets.map( __A, batched=__A, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=__A ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase__ = tokenized_datasets.rename_column("label", "labels" ) def collate_fn(__A ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__A, padding="max_length", max_length=128, return_tensors="pt" ) return tokenizer.pad(__A, padding="longest", return_tensors="pt" ) # Instantiate dataloaders. UpperCAmelCase__ = DataLoader( tokenized_datasets["train"], shuffle=__A, collate_fn=__A, batch_size=__A ) UpperCAmelCase__ = DataLoader( tokenized_datasets["validation"], shuffle=__A, collate_fn=__A, batch_size=__A ) return train_dataloader, eval_dataloader def lowerCAmelCase_ ( __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase__ = config["lr"] UpperCAmelCase__ = int(config["num_epochs"] ) UpperCAmelCase__ = int(config["seed"] ) UpperCAmelCase__ = int(config["batch_size"] ) UpperCAmelCase__ = args.model_name_or_path set_seed(__A ) UpperCAmelCase__ , UpperCAmelCase__ = get_dataloaders(__A, __A, __A, args.n_train, args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase__ = AutoModelForSequenceClassification.from_pretrained(__A, return_dict=__A ) # Instantiate optimizer UpperCAmelCase__ = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase__ = optimizer_cls(params=model.parameters(), lr=__A ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase__ = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: UpperCAmelCase__ = 1 UpperCAmelCase__ = (len(__A ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase__ = get_linear_schedule_with_warmup( optimizer=__A, num_warmup_steps=0, num_training_steps=__A, ) else: UpperCAmelCase__ = DummyScheduler(__A, total_num_steps=__A, 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. UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = accelerator.prepare( __A, __A, __A, __A, __A ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase__ = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase__ = 0 # Now we train the model UpperCAmelCase__ = {} for epoch in range(__A, __A ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(__A ): UpperCAmelCase__ = model(**__A ) UpperCAmelCase__ = outputs.loss UpperCAmelCase__ = loss / gradient_accumulation_steps accelerator.backward(__A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("Memory before entering the train : {}".format(bamb(tracemalloc.begin ) ) ) accelerator.print("Memory consumed at the end of the train (end-begin): {}".format(tracemalloc.used ) ) accelerator.print("Peak Memory consumed during the train (max-begin): {}".format(tracemalloc.peaked ) ) accelerator.print( "Total Peak Memory consumed during the train (max): {}".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) UpperCAmelCase__ = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[f"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, "peak_memory_utilization.json" ), "w" ) as f: json.dump(__A, __A ) def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase__ = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path", type=__A, default="bert-base-cased", help="Path to pretrained model or model identifier from huggingface.co/models.", required=__A, ) parser.add_argument( "--output_dir", type=__A, default=".", help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", ) parser.add_argument( "--peak_memory_upper_bound", type=__A, default=__A, help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.", ) parser.add_argument( "--n_train", type=__A, default=320, help="Number of training examples to use.", ) parser.add_argument( "--n_val", type=__A, default=160, help="Number of validation examples to use.", ) parser.add_argument( "--num_epochs", type=__A, default=1, help="Number of train epochs.", ) UpperCAmelCase__ = parser.parse_args() UpperCAmelCase__ = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} training_function(__A, __A ) if __name__ == "__main__": main()
143
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_longformer''': [ '''LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongformerConfig''', '''LongformerOnnxConfig''', ], '''tokenization_longformer''': ['''LongformerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LongformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LongformerForMaskedLM''', '''LongformerForMultipleChoice''', '''LongformerForQuestionAnswering''', '''LongformerForSequenceClassification''', '''LongformerForTokenClassification''', '''LongformerModel''', '''LongformerPreTrainedModel''', '''LongformerSelfAttention''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLongformerForMaskedLM''', '''TFLongformerForMultipleChoice''', '''TFLongformerForQuestionAnswering''', '''TFLongformerForSequenceClassification''', '''TFLongformerForTokenClassification''', '''TFLongformerModel''', '''TFLongformerPreTrainedModel''', '''TFLongformerSelfAttention''', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
'''simple docstring''' import argparse from collections import defaultdict import yaml a : str = "docs/source/en/_toctree.yml" def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : Dict = defaultdict(__magic_name__ ) for doc in model_doc: counts[doc["local"]] += 1 UpperCAmelCase : List[Any] = [key for key, value in counts.items() if value > 1] UpperCAmelCase : Dict = [] for duplicate_key in duplicates: UpperCAmelCase : Union[str, Any] = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key} ) if len(__magic_name__ ) > 1: raise ValueError( F"{duplicate_key} is present several times in the documentation table of content at " "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " "others." ) # Only add this once new_doc.append({"local": duplicate_key, "title": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1] ) # Sort return sorted(__magic_name__ , key=lambda __magic_name__ : s["title"].lower() ) def lowercase ( __magic_name__=False ): '''simple docstring''' with open(__magic_name__ , encoding="utf-8" ) as f: UpperCAmelCase : Any = yaml.safe_load(f.read() ) # Get to the API doc UpperCAmelCase : Optional[int] = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCAmelCase : Union[str, Any] = content[api_idx]["sections"] # Then to the model doc UpperCAmelCase : Any = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 UpperCAmelCase : str = api_doc[model_idx]["sections"] UpperCAmelCase : Any = [(idx, section) for idx, section in enumerate(__magic_name__ ) if "sections" in section] UpperCAmelCase : Optional[int] = False for idx, modality_doc in modalities_docs: UpperCAmelCase : int = modality_doc["sections"] UpperCAmelCase : int = clean_model_doc_toc(__magic_name__ ) if old_modality_doc != new_modality_doc: UpperCAmelCase : int = True if overwrite: UpperCAmelCase : Dict = new_modality_doc if diff: if overwrite: UpperCAmelCase : Any = model_doc UpperCAmelCase : Any = api_doc with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(__magic_name__ , allow_unicode=__magic_name__ ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") a : Optional[Any] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
311
0
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests lowercase__ = open # noqa: we just need to have a builtin inside this module to test it properly
280
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : str ) -> Tuple: UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) UpperCAmelCase : Dict = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) UpperCAmelCase : Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) UpperCAmelCase : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase : Dict = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase : int = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : str ) -> List[Any]: UpperCAmelCase : Optional[int] = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) UpperCAmelCase : Dict = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1' ): execute_subprocess_async(lowercase_ , env=os.environ.copy() ) if __name__ == "__main__": lowercase__ = Accelerator() lowercase__ = (accelerator.state.process_index + 2, 10) lowercase__ = torch.randint(0, 10, shape).to(accelerator.device) lowercase__ = "" lowercase__ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase__ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase__ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
280
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase = {'''configuration_mbart''': ['''MBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MBartConfig''', '''MBartOnnxConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ['''MBartTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ['''MBartTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ '''MBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MBartForCausalLM''', '''MBartForConditionalGeneration''', '''MBartForQuestionAnswering''', '''MBartForSequenceClassification''', '''MBartModel''', '''MBartPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ '''TFMBartForConditionalGeneration''', '''TFMBartModel''', '''TFMBartPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ '''FlaxMBartForConditionalGeneration''', '''FlaxMBartForQuestionAnswering''', '''FlaxMBartForSequenceClassification''', '''FlaxMBartModel''', '''FlaxMBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys __UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
69
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ : int = [ '''word_embeddings_layernorm.weight''', '''word_embeddings_layernorm.bias''', '''input_layernorm.weight''', '''input_layernorm.bias''', '''post_attention_layernorm.weight''', '''post_attention_layernorm.bias''', '''self_attention.dense.bias''', '''mlp.dense_4h_to_h.bias''', '''ln_f.weight''', '''ln_f.bias''', ] lowerCAmelCase__ : Union[str, Any] = [ '''mlp.dense_4h_to_h.weight''', '''self_attention.dense.weight''', ] def UpperCamelCase__ ( A__ , A__ ) -> List[str]: snake_case__ : Optional[Any] = { 'word_embeddings.weight': 'word_embeddings.weight', 'word_embeddings.norm.weight': 'word_embeddings_layernorm.weight', 'word_embeddings.norm.bias': 'word_embeddings_layernorm.bias', 'weight': 'ln_f.weight', 'bias': 'ln_f.bias', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks snake_case__ : Dict = int(re.match(r'.*layer_(\d*).*' , A__ )[1] ) layer_number -= 3 return F"""h.{layer_number}.""" + key def UpperCamelCase__ ( A__ ) -> str: if dtype == torch.bool: return 1 / 8 snake_case__ : List[str] = re.search(r'[^\d](\d+)$' , str(A__ ) ) if bit_search is None: raise ValueError(F"""`dtype` is not a valid dtype: {dtype}.""" ) snake_case__ : Union[str, Any] = int(bit_search.groups()[0] ) return bit_size // 8 def UpperCamelCase__ ( A__ , A__ , A__ , A__ , A__ ) -> List[str]: # Construct model if bloom_config_file == "": snake_case__ : Union[str, Any] = BloomConfig() else: snake_case__ : int = BloomConfig.from_json_file(A__ ) if shard_model: snake_case__ : Tuple = os.listdir(A__ ) snake_case__ : str = sorted(filter(lambda A__ : s.startswith('layer' ) and "model_00" in s , A__ ) ) snake_case__ : str = {'weight_map': {}, 'metadata': {}} snake_case__ : Optional[int] = 0 snake_case__ : Tuple = None snake_case__ : Any = BloomConfig() for j, file in enumerate(A__ ): print('Processing file: {}'.format(A__ ) ) snake_case__ : str = None for i in range(A__ ): # load all TP files snake_case__ : Optional[int] = file.replace('model_00' , F"""model_0{i}""" ) snake_case__ : int = torch.load(os.path.join(A__ , A__ ) , map_location='cpu' ) # Rename keys in the transformers names snake_case__ : List[Any] = list(temp.keys() ) for key in keys: snake_case__ : List[Any] = temp.pop(A__ ) if tensors is None: snake_case__ : Optional[Any] = temp else: for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case__ : Dict = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case__ : Optional[int] = torch.cat([tensors[key], temp[key]] , dim=A__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case__ : Dict = tensors[key] / pretraining_tp torch.save( A__ , os.path.join( A__ , 'pytorch_model_{}-of-{}.bin'.format(str(j + 1 ).zfill(5 ) , str(len(A__ ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): snake_case__ : List[Any] = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: snake_case__ : Optional[int] = 'pytorch_model_{}-of-{}.bin'.format( str(j + 1 ).zfill(5 ) , str(len(A__ ) ).zfill(5 ) ) snake_case__ : Dict = BloomConfig() snake_case__ : str = pytorch_dump_folder_path + '/' + CONFIG_NAME snake_case__ : int = total_size with open(A__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) with open(os.path.join(A__ , WEIGHTS_NAME + '.index.json' ) , 'w' , encoding='utf-8' ) as f: snake_case__ : List[str] = json.dumps(A__ , indent=2 , sort_keys=A__ ) + '\n' f.write(A__ ) else: snake_case__ : int = BloomModel(A__ ) snake_case__ : Dict = os.listdir(A__ ) snake_case__ : Union[str, Any] = sorted(filter(lambda A__ : s.startswith('layer' ) and "model_00" in s , A__ ) ) snake_case__ : List[str] = None for i, file in enumerate(A__ ): snake_case__ : Dict = None for i in range(A__ ): # load all TP files snake_case__ : List[Any] = file.replace('model_00' , F"""model_0{i}""" ) snake_case__ : int = torch.load(os.path.join(A__ , A__ ) , map_location='cpu' ) # Rename keys in the transformers names snake_case__ : List[str] = list(temp.keys() ) for key in keys: snake_case__ : Any = temp.pop(A__ ) if tensors is None: snake_case__ : Union[str, Any] = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case__ : int = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case__ : Optional[Any] = torch.cat([tensors[key], temp[key]] , dim=A__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case__ : Optional[int] = tensors[key] / pretraining_tp snake_case__ : int = model.load_state_dict(A__ , strict=A__ ) assert not other_keys.unexpected_keys, F"""The keys {other_keys.unexpected_keys} are unexpected""" if missing_keys is None: snake_case__ : List[Any] = set(other_keys.missing_keys ) else: snake_case__ : Tuple = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F"""The keys {missing_keys} are missing""" # Save pytorch-model os.makedirs(A__ , exist_ok=A__ ) snake_case__ : Any = pytorch_dump_folder_path + '/' + WEIGHTS_NAME snake_case__ : List[Any] = pytorch_dump_folder_path + '/' + CONFIG_NAME print(F"""Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}""" ) if config.torch_dtype is not None: snake_case__ : str = model.to(config.torch_dtype ) torch.save(model.state_dict() , A__ ) print(F"""Save configuration file to {pytorch_config_dump_path}""" ) with open(A__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bloom_checkpoint_path''', default=None, type=str, required=True, help='''Path to the Megatron-LM checkpoint path.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--bloom_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--shard_model''', action='''store_true''', help='''An optional setting to shard the output model \nThis enables sharding the converted checkpoint''', ) parser.add_argument( '''--pretraining_tp''', default=4, type=int, help='''Pretraining TP rank that has been used when training the model in Megatron-LM \n''', ) lowerCAmelCase__ : Any = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
143
0
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class SCREAMING_SNAKE_CASE__ : def snake_case_ ( self): torch.manual_seed(0) lowercase__ : Union[str, Any] = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) lowercase__ : List[Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) lowercase__ : Tuple = UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , ) unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests torch.manual_seed(0) lowercase__ : Optional[Any] = DDPMScheduler( num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0_001 , beta_end=0.02 , thresholding=a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , ) torch.manual_seed(0) lowercase__ : int = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case_ ( self): torch.manual_seed(0) lowercase__ : Optional[Any] = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) lowercase__ : int = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5') torch.manual_seed(0) lowercase__ : str = UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , class_embed_type='timestep' , mid_block_scale_factor=1.414 , time_embedding_act_fn='gelu' , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests torch.manual_seed(0) lowercase__ : str = DDPMScheduler( num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0_001 , beta_end=0.02 , thresholding=a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , ) torch.manual_seed(0) lowercase__ : str = DDPMScheduler( num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0_001 , beta_end=0.02 , ) torch.manual_seed(0) lowercase__ : List[Any] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case_ ( self): lowercase__ : Optional[Any] = self.get_dummy_components() lowercase__ : Optional[int] = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) lowercase__ : Union[str, Any] = self.get_dummy_inputs(a) lowercase__ : Any = inputs['prompt'] lowercase__ : str = inputs['generator'] lowercase__ : str = inputs['num_inference_steps'] lowercase__ : List[str] = inputs['output_type'] if "image" in inputs: lowercase__ : List[Any] = inputs['image'] else: lowercase__ : Optional[Any] = None if "mask_image" in inputs: lowercase__ : Union[str, Any] = inputs['mask_image'] else: lowercase__ : Optional[int] = None if "original_image" in inputs: lowercase__ : Tuple = inputs['original_image'] else: lowercase__ : Optional[int] = None lowercase__ , lowercase__ : Union[str, Any] = pipe.encode_prompt(a) # inputs with prompt converted to embeddings lowercase__ : Optional[int] = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: lowercase__ : List[Any] = image if mask_image is not None: lowercase__ : str = mask_image if original_image is not None: lowercase__ : Any = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(a , a , a) lowercase__ : List[Any] = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) lowercase__ : Optional[int] = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f"""`{optional_component}` did not stay set to None after loading.""" , ) lowercase__ : List[Any] = self.get_dummy_inputs(a) lowercase__ : Union[str, Any] = inputs['generator'] lowercase__ : List[Any] = inputs['num_inference_steps'] lowercase__ : Any = inputs['output_type'] # inputs with prompt converted to embeddings lowercase__ : str = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: lowercase__ : List[Any] = image if mask_image is not None: lowercase__ : str = mask_image if original_image is not None: lowercase__ : Any = original_image lowercase__ : int = pipe_loaded(**a)[0] lowercase__ : str = np.abs(to_np(a) - to_np(a)).max() self.assertLess(a , 1e-4) def snake_case_ ( self): lowercase__ : Union[str, Any] = self.get_dummy_components() lowercase__ : List[Any] = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) lowercase__ : List[Any] = self.get_dummy_inputs(a) lowercase__ : str = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) lowercase__ : List[str] = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests lowercase__ : List[str] = self.get_dummy_inputs(a) lowercase__ : str = pipe_loaded(**a)[0] lowercase__ : Union[str, Any] = np.abs(to_np(a) - to_np(a)).max() self.assertLess(a , 1e-4)
216
import numpy as np def snake_case__ ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] ): '''simple docstring''' lowercase__ : List[Any] = int(np.ceil((x_end - xa) / h ) ) lowercase__ : Dict = np.zeros((n + 1,) ) lowercase__ : Dict = ya lowercase__ : Union[str, Any] = xa for k in range(SCREAMING_SNAKE_CASE_ ): lowercase__ : Optional[int] = f(SCREAMING_SNAKE_CASE_ , y[k] ) lowercase__ : Dict = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) lowercase__ : Any = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) lowercase__ : List[Any] = f(x + h , y[k] + h * ka ) lowercase__ : Tuple = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
216
1
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( lowerCAmelCase_ ) -> int: if not nums: return 0 _a : Optional[Any] = nums[0] _a : int = 0 for num in nums[1:]: _a , _a : str = ( max_excluding + num, max(lowerCAmelCase_ , lowerCAmelCase_ ), ) return max(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
89
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , ): '''simple docstring''' super().__init__() self.register_modules(transformer=__UpperCAmelCase , vae=__UpperCAmelCase , scheduler=__UpperCAmelCase ) # create a imagenet -> id dictionary for easier use __UpperCamelCase = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(',' ): __UpperCamelCase = int(__UpperCAmelCase ) __UpperCamelCase = dict(sorted(self.labels.items() ) ) def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCamelCase = list(__UpperCAmelCase ) for l in label: if l not in self.labels: raise ValueError( F'{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.' ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self , __UpperCAmelCase , __UpperCAmelCase = 4.0 , __UpperCAmelCase = None , __UpperCAmelCase = 50 , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , ): '''simple docstring''' __UpperCamelCase = len(__UpperCAmelCase ) __UpperCamelCase = self.transformer.config.sample_size __UpperCamelCase = self.transformer.config.in_channels __UpperCamelCase = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__UpperCAmelCase , device=self.device , dtype=self.transformer.dtype , ) __UpperCamelCase = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents __UpperCamelCase = torch.tensor(__UpperCAmelCase , device=self.device ).reshape(-1 ) __UpperCamelCase = torch.tensor([1000] * batch_size , device=self.device ) __UpperCamelCase = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__UpperCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: __UpperCamelCase = latent_model_input[: len(__UpperCAmelCase ) // 2] __UpperCamelCase = torch.cat([half, half] , dim=0 ) __UpperCamelCase = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) __UpperCamelCase = t if not torch.is_tensor(__UpperCAmelCase ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) __UpperCamelCase = latent_model_input.device.type == 'mps' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCamelCase = torch.floataa if is_mps else torch.floataa else: __UpperCamelCase = torch.intaa if is_mps else torch.intaa __UpperCamelCase = torch.tensor([timesteps] , dtype=__UpperCAmelCase , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: __UpperCamelCase = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __UpperCamelCase = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output __UpperCamelCase = self.transformer( __UpperCAmelCase , timestep=__UpperCAmelCase , class_labels=__UpperCAmelCase ).sample # perform guidance if guidance_scale > 1: __UpperCamelCase , __UpperCamelCase = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] __UpperCamelCase , __UpperCamelCase = torch.split(__UpperCAmelCase , len(__UpperCAmelCase ) // 2 , dim=0 ) __UpperCamelCase = uncond_eps + guidance_scale * (cond_eps - uncond_eps) __UpperCamelCase = torch.cat([half_eps, half_eps] , dim=0 ) __UpperCamelCase = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: __UpperCamelCase , __UpperCamelCase = torch.split(__UpperCAmelCase , __UpperCAmelCase , dim=1 ) else: __UpperCamelCase = noise_pred # compute previous image: x_t -> x_t-1 __UpperCamelCase = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample if guidance_scale > 1: __UpperCamelCase , __UpperCamelCase = latent_model_input.chunk(2 , dim=0 ) else: __UpperCamelCase = latent_model_input __UpperCamelCase = 1 / self.vae.config.scaling_factor * latents __UpperCamelCase = self.vae.decode(__UpperCAmelCase ).sample __UpperCamelCase = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __UpperCamelCase = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __UpperCamelCase = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (samples,) return ImagePipelineOutput(images=__UpperCAmelCase )
360
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def A ( snake_case :List[Any] , snake_case :Dict=1 ) -> Optional[int]: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def A ( snake_case :Dict , snake_case :int=0 ) -> Optional[int]: __UpperCamelCase = [] for old_item in old_list: __UpperCamelCase = old_item.replace('in_layers.0' , 'norm1' ) __UpperCamelCase = new_item.replace('in_layers.2' , 'conv1' ) __UpperCamelCase = new_item.replace('out_layers.0' , 'norm2' ) __UpperCamelCase = new_item.replace('out_layers.3' , 'conv2' ) __UpperCamelCase = new_item.replace('emb_layers.1' , 'time_emb_proj' ) __UpperCamelCase = new_item.replace('skip_connection' , 'conv_shortcut' ) __UpperCamelCase = shave_segments(snake_case , n_shave_prefix_segments=snake_case ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def A ( snake_case :Optional[Any] , snake_case :Tuple=0 ) -> Tuple: __UpperCamelCase = [] for old_item in old_list: __UpperCamelCase = old_item __UpperCamelCase = new_item.replace('norm.weight' , 'group_norm.weight' ) __UpperCamelCase = new_item.replace('norm.bias' , 'group_norm.bias' ) __UpperCamelCase = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) __UpperCamelCase = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) __UpperCamelCase = shave_segments(snake_case , n_shave_prefix_segments=snake_case ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def A ( snake_case :int , snake_case :List[str] , snake_case :List[str] , snake_case :Any=None , snake_case :Optional[int]=None , snake_case :Union[str, Any]=None ) -> Optional[int]: assert isinstance(snake_case , snake_case ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): __UpperCamelCase = old_checkpoint[path] __UpperCamelCase = old_tensor.shape[0] // 3 __UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) __UpperCamelCase = old_tensor.shape[0] // config['num_head_channels'] // 3 __UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) __UpperCamelCase = query.reshape(snake_case ) __UpperCamelCase = key.reshape(snake_case ) __UpperCamelCase = value.reshape(snake_case ) for path in paths: __UpperCamelCase = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here __UpperCamelCase = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) __UpperCamelCase = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) __UpperCamelCase = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: __UpperCamelCase = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: __UpperCamelCase = old_checkpoint[path['old']][:, :, 0] else: __UpperCamelCase = old_checkpoint[path['old']] def A ( snake_case :Optional[Any] , snake_case :Dict ) -> Optional[Any]: __UpperCamelCase = {} __UpperCamelCase = checkpoint['time_embed.0.weight'] __UpperCamelCase = checkpoint['time_embed.0.bias'] __UpperCamelCase = checkpoint['time_embed.2.weight'] __UpperCamelCase = checkpoint['time_embed.2.bias'] __UpperCamelCase = checkpoint['input_blocks.0.0.weight'] __UpperCamelCase = checkpoint['input_blocks.0.0.bias'] __UpperCamelCase = checkpoint['out.0.weight'] __UpperCamelCase = checkpoint['out.0.bias'] __UpperCamelCase = checkpoint['out.2.weight'] __UpperCamelCase = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only __UpperCamelCase = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) __UpperCamelCase = { layer_id: [key for key in checkpoint if f'input_blocks.{layer_id}' in key] for layer_id in range(snake_case ) } # Retrieves the keys for the middle blocks only __UpperCamelCase = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) __UpperCamelCase = { layer_id: [key for key in checkpoint if f'middle_block.{layer_id}' in key] for layer_id in range(snake_case ) } # Retrieves the keys for the output blocks only __UpperCamelCase = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) __UpperCamelCase = { layer_id: [key for key in checkpoint if f'output_blocks.{layer_id}' in key] for layer_id in range(snake_case ) } for i in range(1 , snake_case ): __UpperCamelCase = (i - 1) // (config['num_res_blocks'] + 1) __UpperCamelCase = (i - 1) % (config['num_res_blocks'] + 1) __UpperCamelCase = [key for key in input_blocks[i] if f'input_blocks.{i}.0' in key] __UpperCamelCase = [key for key in input_blocks[i] if f'input_blocks.{i}.1' in key] if f'input_blocks.{i}.0.op.weight' in checkpoint: __UpperCamelCase = checkpoint[ f'input_blocks.{i}.0.op.weight' ] __UpperCamelCase = checkpoint[ f'input_blocks.{i}.0.op.bias' ] continue __UpperCamelCase = renew_resnet_paths(snake_case ) __UpperCamelCase = {'old': f'input_blocks.{i}.0', 'new': f'down_blocks.{block_id}.resnets.{layer_in_block_id}'} __UpperCamelCase = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( snake_case , snake_case , snake_case , additional_replacements=[meta_path, resnet_op] , config=snake_case ) if len(snake_case ): __UpperCamelCase = renew_attention_paths(snake_case ) __UpperCamelCase = { 'old': f'input_blocks.{i}.1', 'new': f'down_blocks.{block_id}.attentions.{layer_in_block_id}', } __UpperCamelCase = { f'input_blocks.{i}.1.qkv.bias': { 'key': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', 'query': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', 'value': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'input_blocks.{i}.1.qkv.weight': { 'key': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', 'query': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', 'value': f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( snake_case , snake_case , snake_case , additional_replacements=[meta_path] , attention_paths_to_split=snake_case , config=snake_case , ) __UpperCamelCase = middle_blocks[0] __UpperCamelCase = middle_blocks[1] __UpperCamelCase = middle_blocks[2] __UpperCamelCase = renew_resnet_paths(snake_case ) assign_to_checkpoint(snake_case , snake_case , snake_case , config=snake_case ) __UpperCamelCase = renew_resnet_paths(snake_case ) assign_to_checkpoint(snake_case , snake_case , snake_case , config=snake_case ) __UpperCamelCase = renew_attention_paths(snake_case ) __UpperCamelCase = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( snake_case , snake_case , snake_case , attention_paths_to_split=snake_case , config=snake_case ) for i in range(snake_case ): __UpperCamelCase = i // (config['num_res_blocks'] + 1) __UpperCamelCase = i % (config['num_res_blocks'] + 1) __UpperCamelCase = [shave_segments(snake_case , 2 ) for name in output_blocks[i]] __UpperCamelCase = {} for layer in output_block_layers: __UpperCamelCase , __UpperCamelCase = layer.split('.' )[0], shave_segments(snake_case , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(snake_case ) else: __UpperCamelCase = [layer_name] if len(snake_case ) > 1: __UpperCamelCase = [key for key in output_blocks[i] if f'output_blocks.{i}.0' in key] __UpperCamelCase = [key for key in output_blocks[i] if f'output_blocks.{i}.1' in key] __UpperCamelCase = renew_resnet_paths(snake_case ) __UpperCamelCase = renew_resnet_paths(snake_case ) __UpperCamelCase = {'old': f'output_blocks.{i}.0', 'new': f'up_blocks.{block_id}.resnets.{layer_in_block_id}'} assign_to_checkpoint(snake_case , snake_case , snake_case , additional_replacements=[meta_path] , config=snake_case ) if ["conv.weight", "conv.bias"] in output_block_list.values(): __UpperCamelCase = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) __UpperCamelCase = checkpoint[ f'output_blocks.{i}.{index}.conv.weight' ] __UpperCamelCase = checkpoint[ f'output_blocks.{i}.{index}.conv.bias' ] # Clear attentions as they have been attributed above. if len(snake_case ) == 2: __UpperCamelCase = [] if len(snake_case ): __UpperCamelCase = renew_attention_paths(snake_case ) __UpperCamelCase = { 'old': f'output_blocks.{i}.1', 'new': f'up_blocks.{block_id}.attentions.{layer_in_block_id}', } __UpperCamelCase = { f'output_blocks.{i}.1.qkv.bias': { 'key': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', 'query': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', 'value': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'output_blocks.{i}.1.qkv.weight': { 'key': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', 'query': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', 'value': f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( snake_case , snake_case , snake_case , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=snake_case , ) else: __UpperCamelCase = renew_resnet_paths(snake_case , n_shave_prefix_segments=1 ) for path in resnet_0_paths: __UpperCamelCase = '.'.join(['output_blocks', str(snake_case ), path['old']] ) __UpperCamelCase = '.'.join(['up_blocks', str(snake_case ), 'resnets', str(snake_case ), path['new']] ) __UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": UpperCamelCase : Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the architecture.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : Optional[Any] = torch.load(args.checkpoint_path) with open(args.config_file) as f: UpperCamelCase : int = json.loads(f.read()) UpperCamelCase : Dict = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] UpperCamelCase : Optional[Any] = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: UpperCamelCase : List[Any] = DDPMScheduler.from_config("/".join(args.checkpoint_path.split("/")[:-1])) UpperCamelCase : Optional[int] = VQModel.from_pretrained("/".join(args.checkpoint_path.split("/")[:-1])) UpperCamelCase : Dict = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
263
0
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def __lowerCamelCase ( A__ = 8 ) -> str: """simple docstring""" UpperCamelCase = ascii_letters + digits + punctuation return "".join(secrets.choice(A__ ) for _ in range(A__ ) ) def __lowerCamelCase ( A__ , A__ ) -> str: """simple docstring""" # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(A__ ) UpperCamelCase = i // 3 UpperCamelCase = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) UpperCamelCase = ( chars_incl + random(A__ , quotient + remainder ) + random(A__ , A__ ) + random(A__ , A__ ) ) UpperCamelCase = list(A__ ) shuffle(A__ ) return "".join(A__ ) # random is a generalised function for letters, characters and numbers def __lowerCamelCase ( A__ , A__ ) -> str: """simple docstring""" return "".join(secrets.choice(A__ ) for _ in range(A__ ) ) def __lowerCamelCase ( A__ , A__ ) -> Dict: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( A__ , A__ ) -> Any: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( A__ , A__ ) -> Union[str, Any]: """simple docstring""" pass # Put your code here... def __lowerCamelCase ( A__ , A__ = 8 ) -> bool: """simple docstring""" if len(A__ ) < min_length: # Your Password must be at least 8 characters long return False UpperCamelCase = any(char in ascii_uppercase for char in password ) UpperCamelCase = any(char in ascii_lowercase for char in password ) UpperCamelCase = any(char in digits for char in password ) UpperCamelCase = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" UpperCamelCase = int(input('Please indicate the max length of your password: ' ).strip() ) UpperCamelCase = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' , password_generator(A__ ) ) print( 'Alternative Password generated:' , alternative_password_generator(A__ , A__ ) , ) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
28
"""simple docstring""" from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _A = 10 def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> int: for i in range(lowerCAmelCase , lowerCAmelCase ): if array[i] == target: return i return -1 def a__ ( lowerCAmelCase , lowerCAmelCase ) -> int: UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Dict = len(lowerCAmelCase ) while left <= right: if right - left < precision: return lin_search(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = (left + right) // 3 + 1 UpperCAmelCase__ : Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCAmelCase__ : str = one_third - 1 elif array[two_third] < target: UpperCAmelCase__ : Tuple = two_third + 1 else: UpperCAmelCase__ : Any = one_third + 1 UpperCAmelCase__ : str = two_third - 1 else: return -1 def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> int: if left < right: if right - left < precision: return lin_search(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[str] = (left + right) // 3 + 1 UpperCAmelCase__ : Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowerCAmelCase , one_third - 1 , lowerCAmelCase , lowerCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowerCAmelCase , lowerCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() _A = input("""Enter numbers separated by comma:\n""").strip() _A = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." _A = int(input("""Enter the number to be found in the list:\n""").strip()) _A = ite_ternary_search(collection, target) _A = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
171
0
def __lowerCamelCase ( __a :int = 3 , __a :int = 7 , __a :int = 1_0_0_0_0_0_0 ) -> int: """simple docstring""" A__ = 0 A__ = 1 for current_denominator in range(1 , limit + 1 ): A__ = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: A__ = current_numerator A__ = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_0_0_0_0_0_0))
276
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class A : '''simple docstring''' __lowerCamelCase : Optional[Any] = BlenderbotSmallConfig __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : List[Any] = '''gelu''' def __init__( self : Dict , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str]=13 , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : Union[str, Any]=99 , __lowerCAmelCase : Union[str, Any]=32 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : Optional[Any]=4 , __lowerCAmelCase : Tuple=37 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : List[str]=20 , __lowerCAmelCase : Union[str, Any]=2 , __lowerCAmelCase : Dict=1 , __lowerCAmelCase : int=0 , ) -> Any: """simple docstring""" A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def a_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = 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 , ) A__ = prepare_blenderbot_small_inputs_dict(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return config, inputs_dict def a_ ( self : Union[str, Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] ) -> str: """simple docstring""" A__ = TFBlenderbotSmallModel(config=__lowerCAmelCase ).get_decoder() A__ = inputs_dict["""input_ids"""] A__ = input_ids[:1, :] A__ = inputs_dict["""attention_mask"""][:1, :] A__ = inputs_dict["""head_mask"""] A__ = 1 # first forward pass A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , head_mask=__lowerCAmelCase , use_cache=__lowerCAmelCase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] A__ = 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 A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCAmelCase , __lowerCAmelCase , rtol=1e-3 ) def __lowerCamelCase ( __a :Dict , __a :Tuple , __a :List[Any] , __a :List[str]=None , __a :List[Any]=None , __a :Optional[Any]=None , __a :List[str]=None , __a :int=None , ) -> Optional[Any]: """simple docstring""" if attention_mask is None: A__ = tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = 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 A (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Tuple = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase : List[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase : Tuple = ( { '''conversational''': TFBlenderbotSmallForConditionalGeneration, '''feature-extraction''': TFBlenderbotSmallModel, '''summarization''': TFBlenderbotSmallForConditionalGeneration, '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration, '''translation''': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase : Dict = True __lowerCamelCase : Optional[Any] = False __lowerCamelCase : Tuple = False def a_ ( self : Tuple ) -> Optional[int]: """simple docstring""" A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=__lowerCAmelCase ) def a_ ( self : List[str] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def a_ ( self : List[str] ) -> Any: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCAmelCase ) @require_tokenizers @require_tf class A (unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = [ '''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ''' ''' i\'m going to throw up.\nand why is that?''' ] __lowerCamelCase : Optional[int] = '''facebook/blenderbot_small-90M''' @cached_property def a_ ( self : Optional[int] ) -> List[str]: """simple docstring""" return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def a_ ( self : List[str] ) -> List[str]: """simple docstring""" A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def a_ ( self : int ) -> Optional[Any]: """simple docstring""" A__ = self.tokenizer(self.src_text , return_tensors="""tf""" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCAmelCase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCAmelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
276
1
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__)
244
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 A_ : def __init__( self , _A , _A=1_4 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=True , _A=9_9 , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=1_6 , _A=2 , _A=0.02 , _A=3 , _A=4 , _A=None , ): '''simple docstring''' UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_input_mask UpperCAmelCase = use_labels UpperCAmelCase = use_mc_token_ids UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope UpperCAmelCase = self.vocab_size - 1 def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase = None if self.use_mc_token_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = self.get_config() UpperCAmelCase = 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 _lowercase ( self ): '''simple docstring''' 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 _lowercase ( self , _A , _A , _A , _A , _A , *_A ): '''simple docstring''' UpperCAmelCase = CTRLModel(config=_A ) model.to(_A ) model.eval() model(_A , token_type_ids=_A , head_mask=_A ) model(_A , token_type_ids=_A ) UpperCAmelCase = model(_A ) 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 _lowercase ( self , _A , _A , _A , _A , _A , *_A ): '''simple docstring''' UpperCAmelCase = CTRLLMHeadModel(_A ) model.to(_A ) model.eval() UpperCAmelCase = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def _lowercase ( self , _A , _A , _A , _A , *_A ): '''simple docstring''' UpperCAmelCase = self.num_labels UpperCAmelCase = CTRLForSequenceClassification(_A ) model.to(_A ) model.eval() UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class A_ (a_ , a_ , a_ , unittest.TestCase ): UpperCAmelCase__ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () UpperCAmelCase__ = (CTRLLMHeadModel,) if is_torch_available() else () UpperCAmelCase__ = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ = True UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase ( self , _A , _A , _A , _A , _A ): '''simple docstring''' 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 _lowercase ( self ): '''simple docstring''' UpperCAmelCase = CTRLModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=_A , n_embd=3_7 ) def _lowercase ( self ): '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def _lowercase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_A ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_A ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _lowercase ( self ): '''simple docstring''' pass @slow def _lowercase ( self ): '''simple docstring''' for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = CTRLModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def _lowercase ( self ): '''simple docstring''' pass @require_torch class A_ (unittest.TestCase ): def _lowercase ( self ): '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_A ) UpperCAmelCase = torch.tensor( [[1_1_8_5_9, 0, 1_6_1_1, 8]] , dtype=torch.long , device=_A ) # Legal the president is UpperCAmelCase = [ 1_1_8_5_9, 0, 1_6_1_1, 8, 5, 1_5_0, 2_6_4_4_9, 2, 1_9, 3_4_8, 4_6_9, 3, 2_5_9_5, 4_8, 2_0_7_4_0, 2_4_6_5_3_3, 2_4_6_5_3_3, 1_9, 3_0, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a UpperCAmelCase = model.generate(_A , do_sample=_A ) self.assertListEqual(output_ids[0].tolist() , _A )
273
0
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Union[str, Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = "\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",\n author = \"Moosavi, Nafise Sadat and\n Strube, Michael\",\n booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",\n month = aug,\n year = \"2016\",\n address = \"Berlin, Germany\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/P16-1060\",\n doi = \"10.18653/v1/P16-1060\",\n pages = \"632--642\",\n}\n\n" UpperCAmelCase_ : Any = "\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n" UpperCAmelCase_ : str = "\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting 'keep_singletons=False', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n 'mentions': mentions\n 'muc': MUC metric [Vilain et al, 1995]\n 'bcub': B-cubed [Bagga and Baldwin, 1998]\n 'ceafe': CEAFe [Luo et al., 2005]\n 'lea': LEA [Moosavi and Strube, 2016]\n 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric('coval')\n >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -',\n ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)',\n ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)',\n ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -',\n ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -',\n ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {'mentions/recall': 1.0,[...] 'conll_score': 100.0}\n" def UpperCamelCase ( _A : Union[str, Any] , _A : Tuple , _A : str=False , _A : Optional[Any]=False , _A : Any=True , _A : Union[str, Any]=False , _A : Dict="dummy_doc" )-> Union[str, Any]: """simple docstring""" A__ = {doc: key_lines} A__ = {doc: sys_lines} A__ = {} A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ = 0 A__ , A__ = reader.get_doc_mentions(_A , key_doc_lines[doc] , _A ) key_singletons_num += singletons_num if NP_only or min_span: A__ = reader.set_annotated_parse_trees(_A , key_doc_lines[doc] , _A , _A ) A__ , A__ = reader.get_doc_mentions(_A , sys_doc_lines[doc] , _A ) sys_singletons_num += singletons_num if NP_only or min_span: A__ = reader.set_annotated_parse_trees(_A , key_doc_lines[doc] , _A , _A ) if remove_nested: A__ , A__ = reader.remove_nested_coref_mentions(_A , _A ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters A__ , A__ = reader.remove_nested_coref_mentions(_A , _A ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters A__ = reader.get_mention_assignments(_A , _A ) A__ = reader.get_mention_assignments(_A , _A ) A__ = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " f"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}""" ) logger.info( "Number of resulting singleton clusters in the key " f"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}""" ) if not keep_singletons: logger.info( f"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """ "files, respectively" ) return doc_coref_infos def UpperCamelCase ( _A : List[str] , _A : Union[str, Any] , _A : Tuple , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] )-> List[str]: """simple docstring""" A__ = get_coref_infos(_A , _A , _A , _A , _A , _A ) A__ = {} A__ = 0 A__ = 0 for name, metric in metrics: A__ , A__ , A__ = evaluator.evaluate_documents(_A , _A , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f"""{name}/recall""": recall, f"""{name}/precision""": precision, f"""{name}/f1""": fa} ) logger.info( name.ljust(10 ) , f"""Recall: {recall * 100:.2f}""" , f""" Precision: {precision * 100:.2f}""" , f""" F1: {fa * 100:.2f}""" , ) if conll_subparts_num == 3: A__ = (conll / 3) * 100 logger.info(f"""CoNLL score: {conll:.2f}""" ) output_scores.update({"conll_score": conll} ) return output_scores def UpperCamelCase ( _A : Tuple )-> List[str]: """simple docstring""" A__ = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: A__ = line.split()[5] if not parse_col == "-": A__ = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def __A ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=True , UpperCAmelCase__=False , UpperCAmelCase__=False , UpperCAmelCase__=False ): A__ = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: A__ = util.check_gold_parse_annotation(UpperCAmelCase__ ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" A__ = evaluate( key_lines=UpperCAmelCase__ , sys_lines=UpperCAmelCase__ , metrics=UpperCAmelCase__ , NP_only=UpperCAmelCase__ , remove_nested=UpperCAmelCase__ , keep_singletons=UpperCAmelCase__ , min_span=UpperCAmelCase__ , ) return score
369
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase ( _A : Optional[int] )-> List[Any]: """simple docstring""" A__ = FileLock(str(tmpdir / "foo.lock" ) ) A__ = FileLock(str(tmpdir / "foo.lock" ) ) A__ = 0.01 with locka.acquire(): with pytest.raises(_A ): A__ = time.time() locka.acquire(_A ) assert time.time() - _start > timeout def UpperCamelCase ( _A : str )-> List[Any]: """simple docstring""" A__ = "a" * 1000 + ".lock" A__ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(_A ) assert len(os.path.basename(locka._lock_file ) ) <= 255 A__ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(_A ): locka.acquire(0 )
198
0
'''simple docstring''' def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: bool = False ): if not isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = F"Expected string as input, found {type(_lowerCamelCase )}" raise ValueError(_lowerCamelCase ) if not isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : str = F"Expected boolean as use_pascal parameter, found {type(_lowerCamelCase )}" raise ValueError(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = input_str.split("""_""" ) __SCREAMING_SNAKE_CASE : List[Any] = 0 if use_pascal else 1 __SCREAMING_SNAKE_CASE : Dict = words[start_index:] __SCREAMING_SNAKE_CASE : Optional[int] = [word[0].upper() + word[1:] for word in words_to_capitalize] __SCREAMING_SNAKE_CASE : str = """""" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
112
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCamelCase__ : List[Any] = [ '''EAGER''', '''AOT_EAGER''', '''INDUCTOR''', '''NVFUSER''', '''AOT_NVFUSER''', '''AOT_CUDAGRAPHS''', '''OFI''', '''FX2TRT''', '''ONNXRT''', '''IPEX''', ] def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: Union[str, Any]=None , _lowerCamelCase: Optional[int]=None , _lowerCamelCase: str=None ): __SCREAMING_SNAKE_CASE : Optional[int] = True while ask_again: __SCREAMING_SNAKE_CASE : Tuple = input(_lowerCamelCase ) try: if default is not None and len(_lowerCamelCase ) == 0: return default return convert_value(_lowerCamelCase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowerCamelCase ) def lowerCAmelCase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: Union[str, Any]=[] , _lowerCamelCase: List[Any]=None , _lowerCamelCase: Optional[Any]=0 ): __SCREAMING_SNAKE_CASE : Union[str, Any] = BulletMenu(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = menu.run(default_choice=_lowerCamelCase ) return convert_value(_lowerCamelCase ) if convert_value is not None else result def lowerCAmelCase_ ( _lowerCamelCase: Optional[Any] ): __SCREAMING_SNAKE_CASE : List[str] = int(_lowerCamelCase ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def lowerCAmelCase_ ( _lowerCamelCase: Any ): __SCREAMING_SNAKE_CASE : str = int(_lowerCamelCase ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def lowerCAmelCase_ ( _lowerCamelCase: Tuple ): __SCREAMING_SNAKE_CASE : Tuple = int(_lowerCamelCase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def lowerCAmelCase_ ( _lowerCamelCase: Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = int(_lowerCamelCase ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def lowerCAmelCase_ ( _lowerCamelCase: Tuple ): __SCREAMING_SNAKE_CASE : int = int(_lowerCamelCase ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def lowerCAmelCase_ ( _lowerCamelCase: List[Any] ): return {"yes": True, "no": False}[value.lower()] class _UpperCamelCase ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def UpperCamelCase__ ( self : Tuple , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = super()._format_usage(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = usage.replace("""<command> [<args>] """ , """""" ) return usage
112
1
import torch from diffusers import StableDiffusionPipeline SCREAMING_SNAKE_CASE : Tuple = '''path-to-your-trained-model''' SCREAMING_SNAKE_CASE : Tuple = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('''cuda''') SCREAMING_SNAKE_CASE : Any = '''A photo of sks dog in a bucket''' SCREAMING_SNAKE_CASE : Any = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save('''dog-bucket.png''')
358
"""simple docstring""" def __UpperCAmelCase ( snake_case_ : list ) -> list: """simple docstring""" for i in range(len(snake_case_ ) - 1 , 0 , -1 ): _lowerCAmelCase = False for j in range(snake_case_ , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: _lowerCAmelCase , _lowerCAmelCase = unsorted[j - 1], unsorted[j] _lowerCAmelCase = True for j in range(snake_case_ ): if unsorted[j] > unsorted[j + 1]: _lowerCAmelCase , _lowerCAmelCase = unsorted[j + 1], unsorted[j] _lowerCAmelCase = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE : List[Any] = input('''Enter numbers separated by a comma:\n''').strip() SCREAMING_SNAKE_CASE : List[str] = [int(item) for item in user_input.split(''',''')] print(F'{cocktail_shaker_sort(unsorted) = }')
317
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE_ ( snake_case_ ): __magic_name__: List[str] = "blip_2_vision_model" def __init__( self : Any , _A : Tuple=1408 , _A : Any=6144 , _A : str=39 , _A : int=16 , _A : Tuple=224 , _A : int=14 , _A : Optional[int]="gelu" , _A : List[str]=0.0_0_0_0_1 , _A : List[str]=0.0 , _A : int=1E-10 , _A : Tuple=True , **_A : Optional[Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**_A ) snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[int] = intermediate_size snake_case_ : Tuple = num_hidden_layers snake_case_ : Optional[Any] = num_attention_heads snake_case_ : Dict = patch_size snake_case_ : int = image_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = attention_dropout snake_case_ : Tuple = layer_norm_eps snake_case_ : Tuple = hidden_act snake_case_ : List[str] = qkv_bias @classmethod def UpperCAmelCase_ ( cls : Union[str, Any] , _A : Union[str, os.PathLike] , **_A : Dict ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_A ) snake_case_ ,snake_case_ : Union[str, Any] = cls.get_config_dict(_A , **_A ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(_A , **_A ) class SCREAMING_SNAKE_CASE_ ( snake_case_ ): __magic_name__: Any = "blip_2_qformer" def __init__( self : Optional[int] , _A : Any=30522 , _A : List[Any]=768 , _A : List[str]=12 , _A : Union[str, Any]=12 , _A : List[Any]=3072 , _A : str="gelu" , _A : Any=0.1 , _A : int=0.1 , _A : Tuple=512 , _A : Dict=0.0_2 , _A : Dict=1E-12 , _A : Optional[Any]=0 , _A : List[Any]="absolute" , _A : Dict=2 , _A : str=1408 , **_A : Optional[int] , ) -> Any: """simple docstring""" super().__init__(pad_token_id=_A , **_A ) snake_case_ : Any = vocab_size snake_case_ : Optional[int] = hidden_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : str = hidden_act snake_case_ : str = intermediate_size snake_case_ : int = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : Optional[int] = max_position_embeddings snake_case_ : Tuple = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Dict = position_embedding_type snake_case_ : Optional[int] = cross_attention_frequency snake_case_ : Optional[int] = encoder_hidden_size @classmethod def UpperCAmelCase_ ( cls : Optional[Any] , _A : Union[str, os.PathLike] , **_A : Tuple ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_A ) snake_case_ ,snake_case_ : List[Any] = cls.get_config_dict(_A , **_A ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": snake_case_ : int = config_dict['qformer_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(_A , **_A ) class SCREAMING_SNAKE_CASE_ ( snake_case_ ): __magic_name__: List[Any] = "blip-2" __magic_name__: Optional[int] = True def __init__( self : str , _A : Optional[Any]=None , _A : Union[str, Any]=None , _A : Any=None , _A : Optional[Any]=32 , **_A : int ) -> Union[str, Any]: """simple docstring""" super().__init__(**_A ) if vision_config is None: snake_case_ : Any = {} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: snake_case_ : List[str] = {} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: snake_case_ : List[str] = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) snake_case_ : Union[str, Any] = BlipaVisionConfig(**_A ) snake_case_ : Tuple = BlipaQFormerConfig(**_A ) snake_case_ : Any = text_config['model_type'] if 'model_type' in text_config else 'opt' snake_case_ : Union[str, Any] = CONFIG_MAPPING[text_model_type](**_A ) snake_case_ : Any = self.text_config.tie_word_embeddings snake_case_ : List[Any] = self.text_config.is_encoder_decoder snake_case_ : Optional[Any] = num_query_tokens snake_case_ : List[str] = self.vision_config.hidden_size snake_case_ : Dict = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES snake_case_ : Optional[Any] = 1.0 snake_case_ : Optional[Any] = 0.0_2 @classmethod def UpperCAmelCase_ ( cls : Tuple , _A : BlipaVisionConfig , _A : BlipaQFormerConfig , _A : PretrainedConfig , **_A : List[Any] , ) -> Optional[int]: """simple docstring""" return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_A , ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" snake_case_ : Optional[int] = copy.deepcopy(self.__dict__ ) snake_case_ : Dict = self.vision_config.to_dict() snake_case_ : Union[str, Any] = self.qformer_config.to_dict() snake_case_ : Dict = self.text_config.to_dict() snake_case_ : Optional[int] = self.__class__.model_type return output
327
from __future__ import annotations from collections import namedtuple def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): snake_case_ : Any = namedtuple('result' , 'name value' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('Only one argument must be 0' ) elif power < 0: raise ValueError( 'Power cannot be negative in any electrical/electronics system' ) elif voltage == 0: return result('voltage' , power / current ) elif current == 0: return result('current' , power / voltage ) elif power == 0: return result('power' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
327
1
"""simple docstring""" from __future__ import annotations from math import ceil, floor, sqrt def _snake_case ( UpperCAmelCase_ : int = 200_0000 ): A__ = [0] A__ = 42 for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target A__ = 0 # the area corresponding to the grid that gives the product closest to target A__ = 0 # an estimate of b, using the quadratic formula A__ = 42 # the largest integer less than b_estimate A__ = 42 # the largest integer less than b_estimate A__ = 42 # the triangle number corresponding to b_floor A__ = 42 # the triangle number corresponding to b_ceil A__ = 42 for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): A__ = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 A__ = floor(UpperCAmelCase_ ) A__ = ceil(UpperCAmelCase_ ) A__ = triangle_numbers[b_floor] A__ = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): A__ = triangle_b_first_guess * triangle_a A__ = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): A__ = triangle_b_second_guess * triangle_a A__ = idx_a * b_ceil return area if __name__ == "__main__": print(f"""{solution() = }""")
69
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class a ( _lowerCamelCase ): """simple docstring""" def __init__( self: int , UpperCamelCase: str = "▁" , UpperCamelCase: bool = True , UpperCamelCase: Union[str, AddedToken] = "<unk>" , UpperCamelCase: Union[str, AddedToken] = "</s>" , UpperCamelCase: Union[str, AddedToken] = "<pad>" , ): """simple docstring""" A__ = { """pad""": {"""id""": 0, """token""": pad_token}, """eos""": {"""id""": 1, """token""": eos_token}, """unk""": {"""id""": 2, """token""": unk_token}, } A__ = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): A__ = token_dict["""token"""] A__ = Tokenizer(Unigram() ) A__ = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(""" {2,}""" ) , """ """ ), normalizers.Lowercase(), ] ) A__ = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=UpperCamelCase , add_prefix_space=UpperCamelCase ), pre_tokenizers.Digits(individual_digits=UpperCamelCase ), pre_tokenizers.Punctuation(), ] ) A__ = decoders.Metaspace(replacement=UpperCamelCase , add_prefix_space=UpperCamelCase ) A__ = TemplateProcessing( single=f"""$A {self.special_tokens['eos']['token']}""" , special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])] , ) A__ = { """model""": """SentencePieceUnigram""", """replacement""": replacement, """add_prefix_space""": add_prefix_space, } super().__init__(UpperCamelCase , UpperCamelCase ) def UpperCamelCase ( self: Tuple , UpperCamelCase: Union[str, List[str]] , UpperCamelCase: int = 80_00 , UpperCamelCase: bool = True , ): """simple docstring""" A__ = trainers.UnigramTrainer( vocab_size=UpperCamelCase , special_tokens=self.special_tokens_list , show_progress=UpperCamelCase , ) if isinstance(UpperCamelCase , UpperCamelCase ): A__ = [files] self._tokenizer.train(UpperCamelCase , trainer=UpperCamelCase ) self.add_unk_id() def UpperCamelCase ( self: Union[str, Any] , UpperCamelCase: Union[Iterator[str], Iterator[Iterator[str]]] , UpperCamelCase: int = 80_00 , UpperCamelCase: bool = True , ): """simple docstring""" A__ = trainers.UnigramTrainer( vocab_size=UpperCamelCase , special_tokens=self.special_tokens_list , show_progress=UpperCamelCase , ) self._tokenizer.train_from_iterator(UpperCamelCase , trainer=UpperCamelCase ) self.add_unk_id() def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = json.loads(self._tokenizer.to_str() ) A__ = self.special_tokens["""unk"""]["""id"""] A__ = Tokenizer.from_str(json.dumps(UpperCamelCase ) )
69
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( snake_case__ ): _lowercase : int = ['image_processor', 'tokenizer'] _lowercase : List[str] = 'ChineseCLIPImageProcessor' _lowercase : Optional[Any] = ('BertTokenizer', 'BertTokenizerFast') def __init__( self : Dict , UpperCAmelCase : Optional[Any]=None , UpperCAmelCase : List[Any]=None , **UpperCAmelCase : Any ) -> Any: __lowerCAmelCase: str = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , UpperCAmelCase , ) __lowerCAmelCase: Dict = kwargs.pop('feature_extractor' ) __lowerCAmelCase: List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(UpperCAmelCase , UpperCAmelCase ) __lowerCAmelCase: Optional[Any] = self.image_processor def __call__( self : Any , UpperCAmelCase : Optional[int]=None , UpperCAmelCase : str=None , UpperCAmelCase : Optional[Any]=None , **UpperCAmelCase : str ) -> Union[str, Any]: if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCAmelCase: List[str] = self.tokenizer(UpperCAmelCase , return_tensors=UpperCAmelCase , **UpperCAmelCase ) if images is not None: __lowerCAmelCase: int = self.image_processor(UpperCAmelCase , return_tensors=UpperCAmelCase , **UpperCAmelCase ) if text is not None and images is not None: __lowerCAmelCase: Dict = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase ) , tensor_type=UpperCAmelCase ) def UpperCAmelCase ( self : str , *UpperCAmelCase : List[str] , **UpperCAmelCase : List[Any] ) -> Optional[Any]: return self.tokenizer.batch_decode(*UpperCAmelCase , **UpperCAmelCase ) def UpperCAmelCase ( self : List[str] , *UpperCAmelCase : Optional[Any] , **UpperCAmelCase : str ) -> Optional[Any]: return self.tokenizer.decode(*UpperCAmelCase , **UpperCAmelCase ) @property def UpperCAmelCase ( self : Any ) -> str: __lowerCAmelCase: str = self.tokenizer.model_input_names __lowerCAmelCase: List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def UpperCAmelCase ( self : Dict ) -> Tuple: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , UpperCAmelCase , ) return self.image_processor_class
322
import unittest from transformers import XLMConfig, 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 ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class A_ : def __init__( self : Any , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : str=1_3 , UpperCAmelCase : Optional[Any]=7 , UpperCAmelCase : str=True , UpperCAmelCase : Any=True , UpperCAmelCase : Tuple=True , UpperCAmelCase : Any=True , UpperCAmelCase : Optional[int]=True , UpperCAmelCase : List[str]=False , UpperCAmelCase : Tuple=False , UpperCAmelCase : int=False , UpperCAmelCase : Optional[int]=2 , UpperCAmelCase : Any=9_9 , UpperCAmelCase : str=0 , UpperCAmelCase : Dict=3_2 , UpperCAmelCase : int=5 , UpperCAmelCase : Optional[int]=4 , UpperCAmelCase : Any=0.1 , UpperCAmelCase : str=0.1 , UpperCAmelCase : int=5_1_2 , UpperCAmelCase : str=2 , UpperCAmelCase : Optional[int]=0.02 , UpperCAmelCase : Optional[Any]=2 , UpperCAmelCase : List[str]=4 , UpperCAmelCase : Dict="last" , UpperCAmelCase : int=True , UpperCAmelCase : Dict=None , UpperCAmelCase : Union[str, Any]=0 , ) -> Dict: __lowerCAmelCase: Optional[int] = parent __lowerCAmelCase: Dict = batch_size __lowerCAmelCase: Tuple = seq_length __lowerCAmelCase: Tuple = is_training __lowerCAmelCase: Optional[Any] = use_input_lengths __lowerCAmelCase: List[str] = use_token_type_ids __lowerCAmelCase: Dict = use_labels __lowerCAmelCase: int = gelu_activation __lowerCAmelCase: Optional[int] = sinusoidal_embeddings __lowerCAmelCase: Tuple = causal __lowerCAmelCase: Optional[Any] = asm __lowerCAmelCase: int = n_langs __lowerCAmelCase: Tuple = vocab_size __lowerCAmelCase: List[Any] = n_special __lowerCAmelCase: List[Any] = hidden_size __lowerCAmelCase: Union[str, Any] = num_hidden_layers __lowerCAmelCase: Dict = num_attention_heads __lowerCAmelCase: int = hidden_dropout_prob __lowerCAmelCase: List[str] = attention_probs_dropout_prob __lowerCAmelCase: Dict = max_position_embeddings __lowerCAmelCase: List[str] = type_sequence_label_size __lowerCAmelCase: str = initializer_range __lowerCAmelCase: List[str] = num_labels __lowerCAmelCase: List[str] = num_choices __lowerCAmelCase: Optional[int] = summary_type __lowerCAmelCase: Any = use_proj __lowerCAmelCase: Optional[Any] = scope __lowerCAmelCase: Dict = bos_token_id def UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: __lowerCAmelCase: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase: str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase: Any = None if self.use_input_lengths: __lowerCAmelCase: Optional[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __lowerCAmelCase: str = None if self.use_token_type_ids: __lowerCAmelCase: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __lowerCAmelCase: int = None __lowerCAmelCase: Optional[int] = None __lowerCAmelCase: Optional[int] = None if self.use_labels: __lowerCAmelCase: Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase: Optional[int] = ids_tensor([self.batch_size] , 2 ).float() __lowerCAmelCase: str = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase: Dict = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase ( self : Tuple ) -> List[Any]: return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def UpperCAmelCase ( self : int , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[int] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Dict , UpperCAmelCase : Optional[Any] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : List[str] , ) -> Optional[int]: __lowerCAmelCase: List[str] = XLMModel(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: Any = model(UpperCAmelCase , lengths=UpperCAmelCase , langs=UpperCAmelCase ) __lowerCAmelCase: List[str] = model(UpperCAmelCase , langs=UpperCAmelCase ) __lowerCAmelCase: List[str] = model(UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Dict , UpperCAmelCase : Any , UpperCAmelCase : List[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Tuple , UpperCAmelCase : Dict , ) -> int: __lowerCAmelCase: str = XLMWithLMHeadModel(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: Union[str, Any] = model(UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase ( self : Optional[int] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Dict , UpperCAmelCase : Optional[int] , UpperCAmelCase : Any , UpperCAmelCase : Optional[int] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[str] , UpperCAmelCase : str , UpperCAmelCase : Dict , ) -> List[str]: __lowerCAmelCase: Dict = XLMForQuestionAnsweringSimple(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: str = model(UpperCAmelCase ) __lowerCAmelCase: List[str] = model(UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase ) __lowerCAmelCase: Optional[Any] = outputs 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 UpperCAmelCase ( self : List[str] , UpperCAmelCase : Dict , UpperCAmelCase : List[Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str , UpperCAmelCase : List[str] , UpperCAmelCase : List[Any] , UpperCAmelCase : Any , UpperCAmelCase : Optional[int] , ) -> Tuple: __lowerCAmelCase: Union[str, Any] = XLMForQuestionAnswering(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: List[str] = model(UpperCAmelCase ) __lowerCAmelCase: Union[str, Any] = model( UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase , cls_index=UpperCAmelCase , is_impossible=UpperCAmelCase , p_mask=UpperCAmelCase , ) __lowerCAmelCase: Any = model( UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase , cls_index=UpperCAmelCase , is_impossible=UpperCAmelCase , ) ((__lowerCAmelCase) , ): List[str] = result_with_labels.to_tuple() __lowerCAmelCase: Union[str, Any] = model(UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase ) ((__lowerCAmelCase) , ): List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCAmelCase ( self : Dict , UpperCAmelCase : Dict , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : List[str] , UpperCAmelCase : Any , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : str , UpperCAmelCase : List[str] , ) -> List[Any]: __lowerCAmelCase: Optional[Any] = XLMForSequenceClassification(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: List[Any] = model(UpperCAmelCase ) __lowerCAmelCase: Tuple = model(UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase : str , UpperCAmelCase : int , UpperCAmelCase : str , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : List[str] , UpperCAmelCase : Dict , UpperCAmelCase : Union[str, Any] , ) -> List[Any]: __lowerCAmelCase: Union[str, Any] = self.num_labels __lowerCAmelCase: Tuple = XLMForTokenClassification(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: Optional[int] = model(UpperCAmelCase , attention_mask=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase ( self : str , UpperCAmelCase : Tuple , UpperCAmelCase : str , UpperCAmelCase : Any , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : List[str] , UpperCAmelCase : List[Any] , ) -> Union[str, Any]: __lowerCAmelCase: List[Any] = self.num_choices __lowerCAmelCase: Optional[Any] = XLMForMultipleChoice(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() __lowerCAmelCase: List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase: List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase: Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase: Any = model( UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase ( self : Tuple ) -> int: __lowerCAmelCase: Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ): Union[str, Any] = config_and_inputs __lowerCAmelCase: Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class A_ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _lowercase : Any = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowercase : Any = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowercase : Optional[int] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def UpperCAmelCase ( self : Any , UpperCAmelCase : List[Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : str ) -> int: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase ( self : Any , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Tuple=False ) -> Dict: __lowerCAmelCase: Optional[Any] = super()._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __lowerCAmelCase: str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase ) __lowerCAmelCase: Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase ) return inputs_dict def UpperCAmelCase ( self : Union[str, Any] ) -> int: __lowerCAmelCase: int = XLMModelTester(self ) __lowerCAmelCase: Optional[int] = ConfigTester(self , config_class=UpperCAmelCase , emb_dim=3_7 ) def UpperCAmelCase ( self : List[str] ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self : Dict ) -> List[Any]: __lowerCAmelCase: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*UpperCAmelCase ) def UpperCAmelCase ( self : List[Any] ) -> int: __lowerCAmelCase: Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*UpperCAmelCase ) def UpperCAmelCase ( self : Tuple ) -> Tuple: __lowerCAmelCase: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*UpperCAmelCase ) def UpperCAmelCase ( self : Optional[Any] ) -> Tuple: __lowerCAmelCase: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*UpperCAmelCase ) def UpperCAmelCase ( self : Optional[Any] ) -> Any: __lowerCAmelCase: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*UpperCAmelCase ) def UpperCAmelCase ( self : Tuple ) -> Tuple: __lowerCAmelCase: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*UpperCAmelCase ) def UpperCAmelCase ( self : Any ) -> Any: __lowerCAmelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCAmelCase ) def UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase : int , UpperCAmelCase : Tuple , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Dict , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Optional[int]=False , UpperCAmelCase : Dict=1 ) -> Dict: self.assertIsInstance(UpperCAmelCase , UpperCAmelCase ) self.assertListEqual( [isinstance(UpperCAmelCase , UpperCAmelCase ) for iter_attentions in attentions] , [True] * len(UpperCAmelCase ) ) self.assertEqual(len(UpperCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(UpperCAmelCase ): # adds PAD dummy token __lowerCAmelCase: int = min_length + idx + 1 __lowerCAmelCase: Union[str, Any] = min_length + idx + 1 __lowerCAmelCase: Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(UpperCAmelCase ) ) def UpperCAmelCase ( self : Dict , UpperCAmelCase : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str=False , UpperCAmelCase : Optional[int]=1 ) -> Union[str, Any]: self.assertIsInstance(UpperCAmelCase , UpperCAmelCase ) self.assertListEqual( [isinstance(UpperCAmelCase , UpperCAmelCase ) for iter_hidden_states in hidden_states] , [True] * len(UpperCAmelCase ) , ) self.assertEqual(len(UpperCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(UpperCAmelCase ): # adds PAD dummy token __lowerCAmelCase: Any = min_length + idx + 1 __lowerCAmelCase: str = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(UpperCAmelCase ) , ) pass @slow def UpperCAmelCase ( self : int ) -> Tuple: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase: List[Any] = XLMModel.from_pretrained(UpperCAmelCase ) self.assertIsNotNone(UpperCAmelCase ) @require_torch class A_ ( unittest.TestCase ): @slow def UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: __lowerCAmelCase: Union[str, Any] = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(UpperCAmelCase ) __lowerCAmelCase: Optional[int] = torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=UpperCAmelCase ) # the president __lowerCAmelCase: Union[str, Any] = [ 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference __lowerCAmelCase: str = model.generate(UpperCAmelCase , do_sample=UpperCAmelCase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , UpperCAmelCase )
322
1
'''simple docstring''' import numpy as np def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Tuple: UpperCamelCase = int(np.ceil((x_end - xa) / h ) ) UpperCamelCase = np.zeros((n + 1,) ) UpperCamelCase = ya UpperCamelCase = xa for k in range(__UpperCamelCase ): UpperCamelCase = f(__UpperCamelCase , y[k] ) UpperCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) UpperCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) UpperCamelCase = f(x + h , y[k] + h * ka ) UpperCamelCase = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
183
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger() @dataclass class a_ : lowercase = 42 lowercase = field(default_factory=lowerCamelCase ) lowercase = field(default_factory=lowerCamelCase ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = len(list(m.modules() ) ) == 1 or isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ) or isinstance(_SCREAMING_SNAKE_CASE , nn.BatchNormad ) if has_not_submodules: self.traced.append(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_SCREAMING_SNAKE_CASE ) [x.remove() for x in self.handles] return self @property def A__ ( self ) -> Tuple: """simple docstring""" return list(filter(lambda _SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : lowercase = 42 lowercase = 42 lowercase = 0 lowercase = field(default_factory=lowerCamelCase ) lowercase = field(default_factory=lowerCamelCase ) def __call__( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = Tracker(self.dest )(_SCREAMING_SNAKE_CASE ).parametrized UpperCamelCase = Tracker(self.src )(_SCREAMING_SNAKE_CASE ).parametrized UpperCamelCase = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.src_skip , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.dest_skip , _SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise Exception( F"Numbers of operations are different. Source module has {len(_SCREAMING_SNAKE_CASE )} operations while" F" destination module has {len(_SCREAMING_SNAKE_CASE )}." ) for dest_m, src_m in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F"Transfered from={src_m} to={dest_m}" ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = True )-> Optional[Any]: print(F"Converting {name}..." ) with torch.no_grad(): UpperCamelCase = timm.create_model(__UpperCamelCase , pretrained=__UpperCamelCase ).eval() UpperCamelCase = ResNetForImageClassification(__UpperCamelCase ).eval() UpperCamelCase = ModuleTransfer(src=__UpperCamelCase , dest=__UpperCamelCase ) UpperCamelCase = torch.randn((1, 3, 224, 224) ) module_transfer(__UpperCamelCase ) assert torch.allclose(from_model(__UpperCamelCase ) , our_model(__UpperCamelCase ).logits ), "The model logits don't match the original one." UpperCamelCase = F"resnet{'-'.join(name.split('resnet' ) )}" print(__UpperCamelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=__UpperCamelCase , ) # we can use the convnext one UpperCamelCase = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=__UpperCamelCase , ) print(F"Pushed {checkpoint_name}" ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = True )-> str: UpperCamelCase = """imagenet-1k-id2label.json""" UpperCamelCase = 1000 UpperCamelCase = (1, num_labels) UpperCamelCase = """huggingface/label-files""" UpperCamelCase = num_labels UpperCamelCase = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCamelCase = {int(__UpperCamelCase ): v for k, v in idalabel.items()} UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} UpperCamelCase = partial(__UpperCamelCase , num_labels=__UpperCamelCase , idalabel=__UpperCamelCase , labelaid=__UpperCamelCase ) UpperCamelCase = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(__UpperCamelCase , names_to_config[model_name] , __UpperCamelCase , __UpperCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
183
1
"""simple docstring""" class _SCREAMING_SNAKE_CASE: def __init__( self ,SCREAMING_SNAKE_CASE__ = "" ,SCREAMING_SNAKE_CASE__ = False ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE :dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word __SCREAMING_SNAKE_CASE :int = is_leaf __SCREAMING_SNAKE_CASE :Union[str, Any] = prefix def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> tuple[str, str, str]: """simple docstring""" __SCREAMING_SNAKE_CASE :List[str] = 0 for q, w in zip(self.prefix ,SCREAMING_SNAKE_CASE__ ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> None: """simple docstring""" for word in words: self.insert(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> None: """simple docstring""" if self.prefix == word: __SCREAMING_SNAKE_CASE :Optional[Any] = 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: __SCREAMING_SNAKE_CASE :Optional[Any] = RadixNode(prefix=SCREAMING_SNAKE_CASE__ ,is_leaf=SCREAMING_SNAKE_CASE__ ) else: __SCREAMING_SNAKE_CASE :List[Any] = self.nodes[word[0]] __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Optional[int] = incoming_node.match( SCREAMING_SNAKE_CASE__ ) # 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(SCREAMING_SNAKE_CASE__ ) # 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: __SCREAMING_SNAKE_CASE :Optional[Any] = remaining_prefix __SCREAMING_SNAKE_CASE :Tuple = self.nodes[matching_string[0]] __SCREAMING_SNAKE_CASE :Optional[Any] = RadixNode(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :int = aux_node if remaining_word == "": __SCREAMING_SNAKE_CASE :Dict = True else: self.nodes[matching_string[0]].insert(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> bool: """simple docstring""" __SCREAMING_SNAKE_CASE :List[str] = self.nodes.get(word[0] ,SCREAMING_SNAKE_CASE__ ) if not incoming_node: return False else: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :str = incoming_node.match( SCREAMING_SNAKE_CASE__ ) # 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(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> bool: """simple docstring""" __SCREAMING_SNAKE_CASE :Any = self.nodes.get(word[0] ,SCREAMING_SNAKE_CASE__ ) if not incoming_node: return False else: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :int = incoming_node.match( SCREAMING_SNAKE_CASE__ ) # 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(SCREAMING_SNAKE_CASE__ ) 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: __SCREAMING_SNAKE_CASE :List[str] = list(self.nodes.values() )[0] __SCREAMING_SNAKE_CASE :Tuple = merging_node.is_leaf self.prefix += merging_node.prefix __SCREAMING_SNAKE_CASE :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: __SCREAMING_SNAKE_CASE :List[Any] = False # If there is 1 edge, we merge it with its child else: __SCREAMING_SNAKE_CASE :Optional[int] = list(incoming_node.nodes.values() )[0] __SCREAMING_SNAKE_CASE :List[Any] = merging_node.is_leaf incoming_node.prefix += merging_node.prefix __SCREAMING_SNAKE_CASE :Any = merging_node.nodes return True def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ = 0 ) -> None: """simple docstring""" 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 ( ) -> bool: __SCREAMING_SNAKE_CASE :str = '''banana bananas bandana band apple all beast'''.split() __SCREAMING_SNAKE_CASE :Dict = RadixNode() root.insert_many(a_ ) assert all(root.find(a_ ) 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 ( ) -> None: assert test_trie() def __lowerCamelCase ( ) -> None: __SCREAMING_SNAKE_CASE :Tuple = RadixNode() __SCREAMING_SNAKE_CASE :Optional[Any] = '''banana bananas bandanas bandana band apple all beast'''.split() root.insert_many(a_ ) print('''Words:''' , a_ ) print('''Tree:''' ) root.print_tree() if __name__ == "__main__": main()
191
"""simple docstring""" def __lowerCamelCase ( a_ : list ) -> list: if len(a_ ) < 2: return collection def circle_sort_util(a_ : list , a_ : int , a_ : int ) -> bool: __SCREAMING_SNAKE_CASE :int = False if low == high: return swapped __SCREAMING_SNAKE_CASE :int = low __SCREAMING_SNAKE_CASE :Tuple = high while left < right: if collection[left] > collection[right]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :str = ( collection[right], collection[left], ) __SCREAMING_SNAKE_CASE :Optional[int] = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Tuple = ( collection[right + 1], collection[left], ) __SCREAMING_SNAKE_CASE :Tuple = True __SCREAMING_SNAKE_CASE :int = low + int((high - low) / 2 ) __SCREAMING_SNAKE_CASE :int = circle_sort_util(a_ , a_ , a_ ) __SCREAMING_SNAKE_CASE :Union[str, Any] = circle_sort_util(a_ , mid + 1 , a_ ) return swapped or left_swap or right_swap __SCREAMING_SNAKE_CASE :Optional[Any] = True while is_not_sorted is True: __SCREAMING_SNAKE_CASE :Tuple = circle_sort_util(a_ , 0 , len(a_ ) - 1 ) return collection if __name__ == "__main__": lowerCamelCase_ = input("Enter numbers separated by a comma:\n").strip() lowerCamelCase_ = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
191
1
import os import pytest from attr import dataclass A__ = '''us-east-1''' # defaults region @dataclass class a : __lowerCAmelCase : str __lowerCAmelCase : Optional[int] = """arn:aws:iam::558105141721:role/sagemaker_execution_role""" __lowerCAmelCase : Optional[Any] = { """task_name""": """mnli""", """per_device_train_batch_size""": 16, """per_device_eval_batch_size""": 16, """do_train""": True, """do_eval""": True, """do_predict""": True, """output_dir""": """/opt/ml/model""", """overwrite_output_dir""": True, """max_steps""": 5_00, """save_steps""": 55_00, } __lowerCAmelCase : List[Any] = {**hyperparameters, """max_steps""": 10_00} @property def __lowerCamelCase ( self :Any ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self :Tuple ): return F"""{self.framework}-transfromers-test""" @property def __lowerCamelCase ( self :Optional[Any] ): return F"""./tests/sagemaker/scripts/{self.framework}""" @property def __lowerCamelCase ( self :List[str] ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='''class''' ) def _lowerCAmelCase ( __lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" snake_case__ : Tuple = SageMakerTestEnvironment(framework=request.cls.framework )
44
import math import tensorflow as tf from packaging import version def _lowerCAmelCase ( __lowerCAmelCase ) -> Tuple: """simple docstring""" snake_case__ : List[str] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Dict = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def _lowerCAmelCase ( __lowerCAmelCase ) -> List[str]: """simple docstring""" snake_case__ : Dict = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Tuple = tf.cast(math.pi , x.dtype ) snake_case__ : str = tf.cast(0.044_715 , x.dtype ) snake_case__ : int = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__lowerCAmelCase , 3 )) )) return x * cdf def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[Any]: """simple docstring""" snake_case__ : Dict = tf.convert_to_tensor(__lowerCAmelCase ) return x * tf.tanh(tf.math.softplus(__lowerCAmelCase ) ) def _lowerCAmelCase ( __lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" snake_case__ : List[str] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : str = tf.cast(0.044_715 , x.dtype ) snake_case__ : Optional[Any] = tf.cast(0.7_978_845_608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def _lowerCAmelCase ( __lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" snake_case__ : Optional[int] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Optional[Any] = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def _lowerCAmelCase ( __lowerCAmelCase ) -> str: """simple docstring""" return tf.clip_by_value(_gelu(__lowerCAmelCase ) , -10 , 10 ) def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase=-1 ) -> Optional[Any]: """simple docstring""" snake_case__ , snake_case__ : str = tf.split(__lowerCAmelCase , 2 , axis=__lowerCAmelCase ) return a * tf.math.sigmoid(__lowerCAmelCase ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[int]: """simple docstring""" return tf.keras.activations.gelu(__lowerCAmelCase , approximate=__lowerCAmelCase ) A__ = tf.keras.activations.gelu A__ = approximate_gelu_wrap else: A__ = _gelu A__ = _gelu_new A__ = { '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[int]: """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
44
1